[英]Java - how to sort an array based off of single int
说我有这样一个数组:
[9, 7, 13, 24, 2, 16, 3, 10]
我想根据int 9对数组进行排序,在int 9中,所有小于9的值都在其左侧,而所有较大的值都在其右侧,是否可以使用选择排序的版本?
有点卡在这里
您想要的应该是一种快速排序的步骤。
我做了一些修改,以便您可以将所需的数据透视点作为参数传递:
public static void main(String[] args) {
int[] a = new int[]{9,7,13,24,2,16,3,10};
System.out.println(partition(a,9));//use value 9 as pivot
System.out.println(Arrays.toString(a));
}
private static int partition(int[] a, int pivot){
int pivotIndex = 0;
for(int i=0;i<a.length;i++){//find initial pivot Index
if(a[i]==pivot) {
pivotIndex = i;
break;
}
}
int low = 0;
int high = a.length-1;
while(low<high){
while(low<high&&a[high]>=pivot) high--;
a[pivotIndex] = a[high];
pivotIndex = high;
while(low<high&&a[low]<=pivot) low++;
a[pivotIndex] = a[low];
pivotIndex= low;
}
//Actual pivotIndex finded
a[pivotIndex] = pivot;
return pivotIndex;
}
输出:
3
[3, 7, 2, 9, 24, 16, 13, 10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.