62,614
社区成员
发帖
与我相关
我的任务
分享
package data_structure.sort;
public class Fast_2 {
public static void sort(int[] a) {
sort(a, 0, a.length-1);
}
private static void sort(int[]a,int low,int high) {
int key = a[low];
int k = low;
boolean go = false;
int l = low;
int h = high;
while(l<h){
while(go){
if(a[l]>key){ //正向
a[k] = a[l];
a[l] = key;
go = false;
k = l;
}
l++;
}
while(!go){
if(a[h]<=key){ //反向
a[k] = a[h];
a[h] = key;
go = true;
k = h;
}
h--;
}
}
if((high-low)<2)
return;
sort(a, low, k);
sort(a, k+1, high);
}
public static void main(String[] args) {
int a [] =new int[]{5,3,31,9,8,15,35,7,6,8,9,4,8,10,0};
sort(a);
for (int i : a) {
System.out.print(i+" ");
}
}
}
package data_structure.sort;
public class Fast_2 {
public static void sort(int[] a) {
sort(a, 0, a.length-1,new a());
}
static class a{
int n =1;
}
private static void sort(int[]a,int low,int high,a n) {
System.out.println("第"+n.n+"次排序前");
n.n++;
for (int i : a) {
System.out.print(i+" ");
}
int key = a[low];
int k = low;
boolean go = false;
int l = low;
int h = high;
System.out.println();
System.out.println("-----起始点: a["+low+"]="+key+" -----结束点: a["+high+"]="+a[high]+"-----比较值:"+key+"---步长:"+(high-low));
while(l<=h){
while(go&&l<=h){
if(a[l]>key){ //正向
a[k] = a[l];
a[l] = key;
go = false;
k = l;
}
l++;
}
while(!go&&l<=h){
if(a[h]<=key){ //反向
a[k] = a[h];
a[h] = key;
go = true;
k = h;
}
h--;
}
}
for (int i : a) {
System.out.print(i+" ");
}
System.out.println();
System.out.println();
if((high-low)<2)
return;
if(a[low]==a[high])
return;
if(k>low)
sort(a, low, k,n);
if(high>k+1)
sort(a, k+1, high,n);
}
public static void main(String[] args) {
int a [] =new int[]{7,5,3,31,9,8,15,35,7,6,8,9,4,10,0,20,17,1,18,8,8};
System.out.println("开始排序!");
for (int i : a) {
System.out.print(i+" ");
}
System.out.println();
System.out.println();
sort(a);
for (int i : a) {
System.out.print(i+" ");
}
}
}
谢谢你的帮助我找到原因了,我把你的代码进行了一下优化判断,同样一份数据排序次数降低了几次,当一趟排序后末位数与第一位数相同,则不进入下一次排序,就减少了相同数据的排序次数
private static void sort(int[] a, int low, int high) {
int key = a[low];
int k = low;
int l = low;
int h = high;
while (l < h) {
while (l < h && a[h] >= key) {
h--;
}
a[k] = a[h];
System.out.println("[" + a[h] + "][" + h + "->" + k + "]");
k = h;
while (l < h && a[l] <= key) {
l++;
}
a[k] = a[l];
System.out.println("[" + a[l] + "][" + l + "->" + k + "]");
k = l;
}
a[l] = key;
if (high - low > 1) {
sort(a, low, k);
if (k + 1 < high)
sort(a, k + 1, high);
}
}
public static void main(String[] args) {
int a[] = new int[] { 5, 3, 31, 9, 8, 15, 35, 7, 6, 8, 9, 4, 8, 10, 0 };
for (int i : a) {
System.out.print(i + " ");
}
System.out.println();
sort(a, 0, a.length - 1);
for (int i : a) {
System.out.print(i + " ");
}
}