當前位置:網站首頁>快速排序 + 冒泡排序 + 插入排序 + 選擇排序

快速排序 + 冒泡排序 + 插入排序 + 選擇排序

2022-06-23 07:43:39生產隊的驢兒

代碼

選擇排序

public class Solution {
    
    /** * @param a: an integer array * @return: nothing */
    public void sortIntegers(int[] a) {
    
        // write your code here

        int n = a.length;

        for (int i = 0; i < n - 1; i++){
    
            int min = i;
            for (int j = i + 1; j < n; j++){
    
                if (a[j] < a[min]){
    
                    min = j;
                }
            }
            swap(a, i, min);
        }
    }
     public void swap(int[] a, int index1, int index2){
    
         int temp = a[index1];
         a[index1] = a[index2];
         a[index2] = temp;
     }
}

冒泡排序

// bubble sort
 public class Solution{
    
     public void sortIntegers(int[] a){
    
         int n = a.length;

        for (int i = 0; i < n- 1;i++){
    
             for (int j = 0; j < n - 1 - i; j++){
    
              if (a[j] > a[j+1]) swap(a, j, j+1);
             }
         }
     }

     public void swap(int[] a, int index1, int index2){
    
         int temp = a[index1];
         a[index1] = a[index2];
         a[index2] = temp;
     }
 }

快速排序

public class Solution{
    
    public void sortIntegers(int[] a) {
    
        int low = 0;
        int hight = a.length - 1;
        quickSort(a, low, hight);
    }

    public void quickSort(int[] a, int low, int hight){
    
        
        if (low > hight) return;

        int left, right, pivot;
        
        left = low;
        right = hight;
        pivot = a[left];

        while(left < right){
    
            while(left < right && a[right] >= pivot) right--;

            if (left < right) a[left] = a[right];

            while(left < right && a[left] <= pivot) left++;

            if (left < right) a[right] = a[left];

            if (left == right) a[left] = pivot;
        }

        quickSort(a, low, right - 1);
        quickSort(a, right + 1, hight);
    }
}

快速排序 的視頻 一定看視頻,不要看代碼,直接看代碼 不容易理解
馬士兵什麼的,沒有這個講的簡單易懂,看這個

插入排序

public class Solution{
    
    public void sortIntegers(int[] a){
    
        int n = a.length;
        for (int i = 1; i < n; i++){
    
            int temp = a[i];
            int j = i;

            while (j > 0 && a[j - 1] > temp){
    
                a[j] = a[j - 1]; 
                j--;
            }

            a[j] = temp;
        }
    }
}

https://www.bilibili.com/video/BV1at411T75o?spm_id_from=333.337.search-card.all.click&vd_source=8d8fef6cad2875d6b6b4c08c3a9ac66d

版權聲明
本文為[生產隊的驢兒]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/174/202206230704599424.html

隨機推薦