java排序方法
冒泡排序法
public static void bubble(int []nums){
int temp;
for(int i=0;i<nums.length-1;i++)
{
int flag=0;
for(int j=0;j<nums.length-i-1;j++)
{
if(nums[j]>nums[j+1])
{
temp=nums[j];
nums[j]=nums[j+1];
nums[j+1]=temp;
flag=1;
}
}
if(flag==0) break;
}
}
快速排序法
public static void quick(int []nums,int low,int high){
int start=low;
int end=high;
int key=nums[low];
while(start<end){
while(start<end&&nums[end]>=key)
end--;
if(start<end)
{
nums[start]=nums[end];
start++;
}
while(start<end&&nums[start]<=key)
start++;
if(start<end)
{
nums[end]=nums[start];
end--;
}
nums[start]=key;
quick(nums,low,start-1);
quick(nums,end+1,high);
}
}
直接插入法
public static void insert(int []num){
int i,j;
int temp;
for(i=1;i<num.length;i++){
temp=num[i];
j=i-1;
while(j>=0&&temp<num[j]){
num[j+1]=num[j];
j--;
}
num[j+1]=temp;
}
}
归并排序
public static int []mergesort(int []num,int low,int high){
int mid =(low+high)/2;
if(low<high){
mergesort(num,low,mid);
mergesort(num,mid+1,high);
merge(num,low,mid,high);
}
return num;
}
public static void merge(int []nums,int low,int mid,int high){
int []temp=new int[high-low+1];
int i=low;
int j=mid+1;
int k=0;
while(i<=mid&&j<=high){
if(nums[i]<nums[j]){
temp[k++]=nums[i++];
}else{
temp[k++]=nums[j++];
}
}
while(i<=mid)
temp[k++]=nums[i++];
while(j<=high)
temp[k++]=nums[j++];
for(int m=0;m<temp.length;m++){
nums[m+low]=temp[m];
}
}