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);
}
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:
(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: