2

Ive written the following method which sorts an array by copying the biggest values into another array. I would like to see alternatives to this approach. for example an approach which swaps the values in the primary array itself, thereby eliminating the need for a secondary array to copy the values to.

I do not want to use pre written .net library methods such as Array.sort or etc as my main goal is only to practice in writing algorithms.

also if anyone can tell me the weak points of the below code and its shortcomings and how it can be improved, it would be greatly appreciated.

thank you

private static void sortArray(int[] array)
{
    int[] sorted = new int[array.Length];
    int curMax = 0;      
    int bigIndex = 0;  

    for (int i = 0; i < array.Length; i++)
    {
        for (int j = 0; j < array.Length; j++)
        {
            if (array[j] > curMax)
            {
                bigIndex = j;
                curMax = array[j];
            }
        }

        sorted[i] = array[bigIndex];
        array[bigIndex] = 0;
        curMax = 0;
    }
}

example of bubble sort:

 private static void sortArray(int[] array)
        {

            bool lastExchange;
            do
            {

                lastExchange = false;

                for (int i = 1; i < array.Length; i++)
                {

                    if (array[i - 1] > array[i])
                    {
                        lastExchange = true;
                        int temp = array[i - 1];
                        array[i - 1] = array[i];
                        array[i] = temp;
                    }
                }
            } while (lastExchange);

        }
3
  • 1
    sorting-algorithms.com Commented Mar 31, 2012 at 16:30
  • Your lastExchange variable should be a boolean. It's irrelevent where the last exchange was, you only need to know whether there was an exchange or not. Commented Apr 1, 2012 at 17:16
  • The biggest weakness is that your sorting algorithm has O(n^2) complexity. Try to come up with a O(n log n) sorting algorithm. Commented Apr 10, 2012 at 23:06

4 Answers 4

3

You arlgorithm is (excuse me for saying it), pretty much as inefficient as a sorting algorithm can be. You could for example make it more efficient by simply swapping items in the array instead of leaving unused values in the array. By doing that you will reduce the number of items that you have to look through for each iteration:

private static void sortArray(int[] array) {
  for (int i = 0; i < array.Length; i++) {
    int largest = array[i];
    int largeIndex = i;
    for (int j = i + 1; j < array.Length; j++) {
      if (array[j] > largest) {
        largeIndex = j;
        largest = array[j];
      }
    }
    array[largeIndex] = array[i];
    array[i] = largest;
  }
}

(Another problem with your algorithm is that it doesn't work with negative values, or zero values.)

One of the simplest sorting algorithms is bubble sort:

private static void sortArray(int[] array) {
  bool cont = true;
  while (cont) {
    cont = false;
    for (int i = 1; i < array.Length; i++) {
      if (array[i - 1] > array[i]) {
        cont = true;
        int temp = array[i - 1];
        array[i - 1] = array[i];
        array[i] = temp;
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Why are you providing an implementation snippet, he said "my main goal is only to practice in writing algorithms"?
continue is a reserved keyword in C#, and also your for loop runs through the array once, and the while loop does not keep track of the last exchange(swap), the last exchange either should be at the array[last] or array[0]( depending on ascending or descending sort) at which point the largest value has bubbled to the top and there is no more sorting to do.I've actually ran it in the debugger a couple of times and it certainly did not work. I've put the corrected version in my question.
@farhad: The continue variable name is such an easy fix... Regarding the swaps, you have got the bubble sort algorithm wrong. The swaps are always done between two items that are next to each other. There is an improved version of the bubble sort where you decrease the loop length by one each iteration, as the last item is known to be in the right place, but that's not in the original bubble sort algorithm.
I just tried your updated version, and it still does not sort the array, there is definatly something wron with the order of the while loop and the boolean, try to test it in VS.
@farhad: I did find an error in the code. I just forgot to set the flag to true when there was a swap.
2

Take a look at http://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms for examples of sorting algorithms. You can click through to any one you want and try implementing them yourself based on their description.

What you have at the moment is a selection sort, which is fairly easy to implement but isn't all that great as far as sorting algorithms go. A good sorting algorithm will have an n(log n) complexity (typically a log n search * n items).

Comments

0

Have you already thought about implementing the following sort algorithms:

Bubble Sort Quick Sort

Greetings,

Update 1:
A very good page about sorting algorithms (visualized) is http://www.sorting-algorithms.com/

1 Comment

@farhad great if i could lead you on track.
0

i like Bucket Sort and it's extended Radix-Sort Best ! two reasons:

  1. cant overlook the O(n) over O(nLog(n))
  2. i love hash tables and it is kinda the same concept

Also take a look at Heap Sort, which is a nice algorithem.

4 Comments

I might have missed something, but could you explain how either are similar to hash tables? - just curious, and I can't see it myself.
Imagine a Hash Map function f(x)=f%10;
Hmm, I must be missing something (and I think you meant x%10). No worries.
i agree it isn't hashset per say, it is splitting the array to a limited set of results (0 - 9)... p.s. you are right... it was meant to be x%10.. p.s 2: it isn't really O(n), but when the numbers have a maximum, then there is... i still consider it as O(NlogN)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.