排序总结
冒泡排序
public static int[] bubbleSort(int[] nums){
int i,j,temp,n = nums.length;
boolean flag;
for(i=0;i<n-1;i++){
flag = true;
for(j=0;j<n-i-1;j++){
if(nums[j]>nums[j+1]){
temp = nums[j];
nums[j]=nums[j+1];
nums[j+1]=temp;
flag = false;
}
}
if(flag){
break;
}
}
return nums;
}
选择排序
public static int[] selectionSort(int[] nums){
int i,j,tempIndex,temp,n = nums.length;
for(i=0;i<n-1;i++){
tempIndex = i;
for(j=i+1;j<n;j++){
if(nums[tempIndex]>nums[j]){
tempIndex = j;
}
}
temp = nums[i];
nums[i] = nums[tempIndex];
nums[tempIndex] = temp;
}
return nums;
}
插入排序
public static int[] insertionSort(int[] nums){
int i,j,temp,indexTemp,n=nums.length;
for(i=1;i<n;i++){
temp = nums[i];
indexTemp = i-1;
while (indexTemp>=0 && nums[indexTemp]>temp){
nums[indexTemp+1]=nums[indexTemp];
indexTemp--;
}
nums[indexTemp+1]=temp;
}
return nums;
}
快速排序
public static int[] quickSort(int[] nums,int left,int right){
int l = left,r = right;
int temp;
if(left>=right){
return nums;
}
temp = nums[left];
while (left<right){
while(nums[right]>=temp && left<right){
right--;
}
if(left<right){
nums[left++]=nums[right];
}
while(nums[left]<=temp && left<right){
left++;
}
if(left<right){
nums[right--]=nums[left];
}
}
nums[left]=temp;
nums = quickSort(nums,l,right-1);
nums = quickSort(nums,left+1,r);
return nums;
}
结果
public static void main(String[] args) {
int[] nums = {9,8,7,5,6,1,2,8,0,3,10,1,6};;
}