Reputation: 1
So I'm trying to make an insertion sort program sort numbers in descending order. However, I'm not entirely sure what to do with this specific program.
public static void insertionSort(int[] arr)
{
System.out.println(Arrays.toString(arr));
for (int i = 1; i < arr.length; i++)
{
int curNumber = arr[i];
int curIndex = i+1;
while ( curIndex <= 0 && arr[curIndex] < curNumber)
{
arr[curIndex+1] = arr[curIndex];
curIndex--;
}
arr[curIndex - 1] = curNumber;
System.out.println(Arrays.toString(arr));
}
}
I've tried changing the < to a > on line 9 (while (curIndex <= 0 && arr[curIndex] < curNumber)), under the logic that the greater number will be moved, but it produces entirely wrong values for the sort. What should I do?
Upvotes: 0
Views: 182
Reputation: 1484
You should check if currentIndex is >= 0, also the current index starts at i - 1
public static void insertionSort(int[] arr)
{
System.out.println(Arrays.toString(arr));
for (int i = 1; i < arr.length; i++)
{
int curNumber = arr[i];
int curIndex = i - 1;
while ( curIndex >= 0 && arr[curIndex] < curNumber)
{
arr[curIndex+1] = arr[curIndex];
curIndex--;
}
arr[curIndex + 1] = curNumber;
System.out.println(Arrays.toString(arr));
}
}
Upvotes: 1