1.冒泡排序
public class 冒泡排序 {
public static void main(String[] args) {
int[] nums= {5,6,12,9,7,3};
bubblesort(nums);
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);;
}
}
public static void bubblesort(int[] nums) {
int len=nums.length;
for(int i=0;i<len;i++) {
boolean flag=false;
for(int j=len-1;j>i;j--) {
if(nums[j-1]>nums[j]) {
int temp=nums[j-1];
nums[j-1]=nums[j];
nums[j]=temp;
flag=true;
}
}
if(flag==false)
return;
}
}
}
2.快速排序
public class 快速 {
public static void main(String[] args) {
int[] nums= {5,6,12,9,7,3,3};
quicksort(nums,0,nums.length-1);
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");;
}
}
public static void quicksort(int[] nums,int low,int high) {
if(low<high) {
int pivotpos=partion(nums, low, high);
quicksort(nums, low, pivotpos-1);
quicksort(nums, pivotpos+1, high);
}
}
public static int partion(int[] nums,int low,int high) {
int pivot=nums[low];
while(low<high) {
while(low<high&&nums[high]>=pivot) high--;
nums[low]=nums[high];
while(low<high&&nums[low]<=pivot) low++;
nums[high]=nums[low];
}
nums[low]=pivot;
return low;
}
}
3.归并排序
public class 归并 {
public static void main(String[] args) {
int[] nums= {5,6,12,9,7,3,3};
mergesort(nums,0,nums.length-1);
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");;
}
}
public static void mergesort(int[] nums,int low,int high) {
if(low<high) {
int mid=low+high>>1;
mergesort(nums, low, mid);
mergesort(nums, mid+1, high);
merge(nums,low,mid,high);
}
}
public static void merge(int[] nums,int low,int mid,int high) {
int[] b=Arrays.copyOf(nums, nums.length);
int i,j,k;
for(i=low,j=mid+1,k=i;i<=mid&&j<=high;k++) {
if(b[i]<b[j])
nums[k]=b[i++];
else
nums[k]=b[j++];
}
while(i<=mid) nums[k++]=b[i++];
while(j<=high)nums[k++]=b[j++];
}
}