一、題目
標題:三部排序
一般的排序有許多經典算法,如快速排序、希爾排序等。
但實際應用時,經常會或多或少有一些特殊的要求。我們沒必要套用那些經典算法,可以根據實際情況建立更好的解法。
比如,對一個整型數組中的數字進行分類排序:
使得負數都靠左端,正數都靠右端,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{ //元素等於0
--------------------//填空
}
}
}
如果給定數組:
25,18,-2,0,16,-5,33,21,0,19,-16,25,-3,0
則排序後爲:
-3,-2,-16,-5,0,0,0,21,19,33,25,16,18,25
*
二、思路
1.首先理解代碼,最好可以手畫出前兩個條件語句的流程
2.觀察代碼邏輯,發現填空處應爲x[p]等於0的情況
3.極限思想:可以考慮所有的元素都是0,也要保證比較繼續進行,所以p++;然後驗證,非常簡單。
三、代碼
package shengsai;
public class sanbupaixu {
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{ //元素等於0
p++;
///填空
}
}
}
//寫一個main函數進行驗證
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]);
}
}
}