463. 整数排序---选择排序,冒泡排序,插入排序

描述
给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。
样例
样例 1:
输入: [3, 2, 1, 4, 5]
输出: [1, 2, 3, 4, 5]

样例 2:
输入: [1, 1, 2, 1, 1]
输出: [1, 1, 1, 1, 2]

选择排序
它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置

public void sortIntegers(int[] A) {
            // write your code here
            int minIndex;
            int temp;
    for (int i = 0; i <A.length; i++) {
    
        minIndex = i;
        for(int j = i + 1;j <A.length;j++) {
            if (A[minIndex] > A[j]) {
                minIndex = j;
            } 
        }
        temp = A[minIndex];
         A[minIndex] = A[i];
        A[i] = temp;
    } 
}

冒泡排序
依次比较两个相邻的元素,如果他们的顺序(如从大到小、首字母从A到Z)错误就把他们交换过来

 public void sortIntegers(int[] A) {
        // write your code here
        
        int temp;
        for (int i = 0; i <A.length; i++) {
        
            for(int j = 0;j <A.length-i-1;j++) {
                
                if(A[j] > A[j+1]) {
                    temp = A[j];
                    A[j] = A[j+1];
                    A[j+1] = temp; 
                    }
            }
        } 
    }

插入排序
有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序

 public void sortIntegers(int[] A) {
            // write your code here
        
        int index;
        int temp;
        for (int i = 1; i <A.length; i++) {
        
            index = i;
            temp = A[i];
            for(int j = 0;j <i;j++) {
                
                if(A[j] > A[i]) {
                    index = j;
                    break;
                }
            }
              
            for(int start = i; start > index;start--) {
                    A[start] = A[start-1];
            } 
            A[index] = temp; 
        } 
    }
发布了40 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/ai_pple/article/details/87182639