快速排序实现原理:
首先设定一个分界值,通过该分界值将数组分成左右两部分。将大于等于分界值的数据元素放到数组的右边(该分界值的右边),小于分界值的数据元素放到数组的左边(该分界值的左边)。然后,左边和右边的数据分别进行快速排序。排序过程如下:
快速排序算法实现:(不稳定算法)
public static void main(String
[] args
) {
int[] arr
= {6, 1, 2, 7, 9, 3, 4, 5, 8};
sort(arr
);
for (int i
: arr
) {
System
.out
.print(i
+"\t");
}
}
private static boolean less(int v
, int w
) {
return v
< w
;
}
private static void exch(int[] a
, int i
, int j
) {
int temp
= a
[i
];
a
[i
] = a
[j
];
a
[j
] = temp
;
}
public static void sort(int[] a
) {
int lo
= 0;
int hi
= a
.length
- 1;
sort(a
, lo
, hi
);
}
private static void sort(int[] a
, int lo
, int hi
) {
if(hi
<= lo
) {
return ;
}
int partition
= partition(a
, lo
, hi
);
sort(a
, lo
, partition
-1);
sort(a
, partition
+ 1, hi
);
}
private static int partition(int[] a
, int lo
, int hi
) {
int key
= a
[lo
];
int left
= lo
;
int right
= hi
+ 1;
while(true) {
while(less(key
, a
[--right
])) {
if(right
== lo
) {
break;
}
}
while(less(a
[++left
], key
)) {
if(left
== hi
) {
break;
}
}
if(left
>= right
) {
break;
} else {
exch(a
, left
, right
);
}
}
exch(a
, lo
, right
);
return right
;
}
程序执行结果:
转载请注明原文地址:https://blackberry.8miu.com/read-35323.html