栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

快速排序 + 冒泡排序 + 插入排序 + 选择排序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

快速排序 + 冒泡排序 + 插入排序 + 选择排序

代码 选择排序
public class Solution {
    
    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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/986160.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号