[英]Insertion Sort from Right to Left
I am trying to learn Insertion Sort in Java but I have a problem. 我正在尝试学习Java中的插入排序,但是我遇到了问题。 I learned the insertion sort in ascending order. 我按升序学习了插入排序。 Now, I need to do it in descending order but I have to start sorting the array from right to left. 现在,我需要按降序排列,但是我必须开始从右到左对数组进行排序。
public class Sorting {
public static void sort(Comparable[] a) {
int N = a.length;
for (int i = 1; i < N; i++) {
for (int j = i; j > 0 && less(a[j], a[j - 1]); j--)
swap(a, j, j - 1);
}
}
private static void swap(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
} }
The code which is above sorts the array from left to right in ascending order(1,2,3,4,..). 上面的代码按从左到右的升序(1,2,3,4,..)对数组进行排序。
I need to change it in descending order but sorts from right to left(5,4,3,2..). 我需要按降序更改它,但从右到左排序(5,4,3,2 ..)。 I change the code and tried this: 我更改了代码并尝试了此操作:
public static void sort(Comparable[] a) {
int N = a.length;
for (int i = N-1; i>=0; i--) {
for (int j = i; j >= 1 && less(a[j-1], a[j]); j++)
swap(a, j, j-1);
}
}
I changed the sort method several times but I got errors.. 我多次更改了排序方法,但出现错误。
Use the same algorithm, just in the check, which is smaller, exchange the arguments for the method less
such that: less(a[j - 1], a[j])
. 使用相同的算法,只是在检查,这是较小的,交换参数的方法less
,使得: less(a[j - 1], a[j])
Then the smaller elemenets will be shifted to the right. 然后,较小的元素将向右移动。
here, I also tested it, try out: 在这里,我也对其进行了测试,请尝试:
public class InsertionSort {
public static void main(String[] args) {
Comparable[] a = new Comparable[]{5,6,12,1,3,15,4,0,9};
sort(a);
for (int i = 1 ; i < a.length; i++)
assert a[i].compareTo(a[i-1]) >= 0;
System.out.println("sort is correct");
}
public static void sort(Comparable[] a) { // Sort a[] into increasing order.
int N = a.length;
for (int i = N - 1; i > 0; i--) { // Insert a[i] among a[i-1], a[i-2],a[i-3]... ..
for (int j = i; j < N && less(a[j - 1], a[j]); j++)
exch(a, j, j - 1);
}
}
private static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.