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);
}
lastExchangevariable should be a boolean. It's irrelevent where the last exchange was, you only need to know whether there was an exchange or not.