Reputation: 45
I am trying to create a selectionSort method to arrange values in descending order. This code arranges them in ascending order. How can I swap this code to arrange it the other way.
public void selectionSort()
{
int n = data.length;
for(int index = 0; index < n-1; index++)
{
int min_idx = index;
for(int j = index+1; j < n; j++)
if(data[j] < data[min_idx])
min_idx = j;
int temp = data[min_idx];
data[min_idx] = data[index];
data[index] = temp;
}
}
Upvotes: 2
Views: 12029
Reputation: 1
public static class SelectionSort
{
static int min;
public static void Sort(int[] data)
{
for (int i = 0; i < data.Length; i++)
{
for (int j = 0; j < data.Length; j++)
{
min = j;
if (data[i] < data[j])
Swap(x: ref data[i], y: ref data[min]);
}
}
}
private static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
}
For Ascending this line
if (data[i] < data[j])
For Descending this line
if (data[i] > data[j])
Upvotes: 0
Reputation: 18255
To solve this problem, I would reccomend you to refactor your code first. Move swap
and findMin
into separate method:
private static int getMin(int[] arr, int from, int to) {
int min = from;
for (int j = from; j < to; j++)
min = arr[j] < arr[min] ? j : min;
return min;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Here, you probably can see, that implementation of ASC
and DESC
sorting are trivial:
public static void selectionSortAsc(int[] arr) {
for (int i = 0; i < arr.length - 1; i++)
swap(arr, getMin(arr, i + 1, arr.length), i);
}
public static void selectionSortDesc(int[] arr) {
for (int i = arr.length - 1; i > 0; i--)
swap(arr, getMin(arr, 0, i + 1), i);
}
Upvotes: 1
Reputation: 311843
Instead of selecting the minimal item in each iteration, you should instead select the maximum one. All you really need to do is change the <
condition to >
, but I've also changed the names accordingly to make the code easier to understand:
public void selectionSort()
{
int n = data.length;
for(int index = 0; index < n-1; index++)
{
int max_idx = index; // max_idx instead of min_idx
for(int j = index+1; j < n; j++)
if(data[j] > data[min_idx]) // > instead of <
max_idx = j;
int temp = data[max_idx];
data[max_idx] = data[index];
data[index] = temp;
}
}
Upvotes: 1
Reputation: 896
As of now I can think of two methods. I haven't tried them but worth giving a try.
Multiply all the numbers by -1 and apply the original selection sort to sort for ascending order. After sorting is complete multiply all the numbers by -1 to get back originwl numbers but now they are sorted in descending order.
Try changing the comparison condition
if(data[j] < data[min_idx])
to
if(data[j] >= data[min_idx])
Let me know if there is some issue with these methods.
Upvotes: 3