三部排序
标题:三部排序
一般的排序有许多经典算法,如快速排序、希尔排序等。
但实际应用时,经常会或多或少有一些特殊的要求。我们没必要套用那些经典算法,可以根据实际情况建立更好的解法。
比如,对一个整型数组中的数字进行分类排序:
使得负数都靠左端,正数都靠右端,0在中部。注意问题的特点是:负数区域和正数区域内并不要求有序。可以利用这个特点通过1次线性扫描就结束战斗!!
static void sort(int[] x)
{
int p = 0;
int left = 0;
int right = x.length-1;
while(p<=right){
if(x[p]<0){
int t = x[left];
x[left] = x[p];
x[p] = t;
left++;
p++;
}
else if(x[p]>0){
int t = x[right];
x[right] = x[p];
x[p] = t;
right--;
}
else{
_________________________; //代码填空位置
}
}
}
————————————————
版权声明:本文为CSDN博主「cledwyn」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cledwyn/article/details/88702534
首先第一步读题
之后就要把代码放在eclipse里面,使它编译通过
public class 三部排序 {
public static void main(String[] args) {
int[] arr = {25, 18, -2, 0, 16, -5, 33, 21, 0, 19, -16, 25, -3, 0};
sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
static void sort(int[] x)
{
int p = 0;
int left = 0;//最小下标
int right = x.length-1;//最大下标
while(p<=right){
if(x[p]<0){
//元素小于0将元素和left位置交换,即交换到最左边
int t = x[left];
x[left] = x[p];
x[p] = t;
left++;
p++;
}
//如果元素大于0将元素和right位置交换
else if(x[p]>0){
int t = x[right];
x[right] = x[p];
x[p] = t;
right--;
}
else{//元素等于0的时候
p++;//代码填空位置
}
}
}
}