常用的排序算法

1.冒泡排序           

private static void bubbleSort(int[] a){
int temp;
int len = a.length; //避免多次执行该操作。
for(int i = 0;i < len; i++){
for(int j = i+1;j<len;j++){
if(a[i] > a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}

}

}

       //打印冒泡排序的结果

for(int i=0;i<len;i++){
System.out.println(a[i]);
}
}

 

2.快速排序

public class QuickSort {
public int data[];
             //找到low所在的最终位置index;
   private int partition(int sortArray[],int low,int hight)
   {
       int key = sortArray[low];
        
       while(low<hight)
       {

          //从后往前
           while(low<hight && sortArray[hight]>=key)
               hight--;
           sortArray[low] = sortArray[hight];
            //从前往后
           while(low<hight && sortArray[low]<=key)
               low++;
           sortArray[hight] = sortArray[low];
       }
       sortArray[low] = key;
       return low;
   }
     //排序重用代码
   public void sort(int low,int hight)
   {
       if(low<hight)
       {
           int result = partition(data,low,hight);
           sort(low,result-1);
           sort(result+1,hight);
       }
        
   }
     //展示层代码
   public void display()
   {
       for(int i=0;i<data.length;i++)
       {
           System.out.print(data[i]);
           System.out.print(" ");
       }
   }
}

//main函数测试

public static void main(String[] args) {
  QuickSort qs = new QuickSort();
       int data[] = {44,22,2,32,54,22,88,77,99,11};
       qs.data = data;
       qs.sort(0, qs.data.length-1);
       qs.display();
}

 

3.插入排序

private static void insertSort(int[] a){
int len = a.length;
for(int i=0;i<len;i++){
for(int j=0;j<len-i;j++){
  if(a[len-i-1] < a[j]){
  int temp = a[len-i-1];
  a[len-i-1] = a[j];
  a[j] = temp;
  }
}
}
for(int f=0;f<len;f++){
System.out.println(a[f]);
}
}

4.二分查找

 

private static int BinSearch(int[] a ,int key){
int low = 0;
int high = a.length;
int mid;
while(low < high){
mid = (low + high)/2;
if(key < a[mid]){
high = mid -1;
}else if( key > a[mid]){
low = mid + 1;
}else if(key == a[mid]){
return mid;
}
}
return -1;
}

 

5.选择排序

逻辑是第一次找到最小的数据与第一个数据交换,第二次找到第二小的数据与第二个数据交换。

private static void SelectSort(int[] a){
int min = 0;
int index = 0;
int len = a.length;
for(int i=0;i<len;i++){
min =a[i];
index =i;
for(int j=i;j<len;j++){
//找到最小的元素,并记录最小元素的索引。
if(min > a[j]){
min = a[j];
index = j;
}
}
//交换顺序
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值