class Sort2 {
//快速排序 nlogn
public static void quick(int[] arr, int beginIndex, int endIndex) {
if (beginIndex >= endIndex) {
return;
}
int keyValue = arr[beginIndex];// 以beginIndex位置的值为键值
// 定义关键位置下标值
int keyIndex = beginIndex;
for (int i = beginIndex + 1; i <= endIndex; i++) {// 循环处理, 在数列中只要找到比键值小的就处理
if (arr[i] < keyValue) {
keyIndex++; // 增加keyIndex位置 用于保存比键值小的值.
int tmp = arr[keyIndex];// 交换KeyIndex位置和i位置的值, 这样keyIndex位置中保存的就是比键值小的值
arr[keyIndex] = arr[i];
arr[i] = tmp;
}
}
int t = arr[beginIndex];// 把开始位置和关键位置进行交换, 使得关键位置处保存的就是键值
arr[beginIndex] = arr[keyIndex];
arr[keyIndex] = t;
// 初步目标完成 : 数组分成3部分, 关键位置左边是比键值小的子列, 关键位置右边是比键值大的子列
quick(arr, beginIndex, keyIndex - 1); // 左边子列递归处理, 左边子列从原始的开始位置开始, 结束于关键位置向左一位
quick(arr, keyIndex + 1, endIndex); // 右边子列递归处理,右边子列从关键位置向右一位开始, 结束于原始结束位置
}
public static void main(String[] args) {
int [] a=new int []{9,5,6,2,1,4,8,3,7,0};
quick( a,0,a.length-1);
for(int tmp : a )
System.out.print(tmp+" ");
}
}
class Sort1 {
//选择排序 每次找到最小值
public static void main(String[] args) {
int [] a=new int []{9,5,6,2,1,4,8,3,7,0};
for(int i=0;i<a.length-1;i++){
int minIndex=i;
for(int j=i+1;j<a.length;j++){
if(a[j]<a[minIndex]){
minIndex=j;
}
}
if(minIndex!=i){
int t=a[i];
a[i]=a[minIndex];
a[minIndex]=t;
}
}
for(int tmp : a )
System.out.print(tmp+" ");
}
}
public class Sort {
//冒泡
public static void main(String[] args) {
int [] a=new int []{9,5,6,2,1,4,8,3,7,0};
for(int i=0;i<a.length-1;i++){
for(int j=0;j<a.length-1-i;j++){
if(a[j]>a[j+1]){
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
for(int tmp : a )
System.out.print(tmp+" ");
}
}
排序
最新推荐文章于 2022-04-26 14:53:52 发布