Lintcode整数排序

来源:互联网 发布:手机桌面特效软件 编辑:程序博客网 时间:2024/06/05 10:35

整数排序 

给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。

Example

对于数组 [3, 2, 1, 4, 5], 排序后为:[1, 2, 3, 4, 5]

插入排序:

public class Solution {
    /*
     * @param A: an integer array
     * @return: 
     */
    public void sortIntegers(int[] A) {
        // write your code here
        int j=0;
        for(int i=1;i<A.length;i++){
            j=i;
            int target=A[j];//记录A[j]的值
            while(j>0&&target<A[j-1]){
                A[j]=A[j-1];
                j--;
            }
            A[j]=target;
        }
    }
}

冒泡排序:

public class Solution {
    /*
     * @param A: an integer array
     * @return: 
     */
    public void sortIntegers(int[] A) {
        // write your code here
        int temp;
        for(int i=0;i<A.length-1;i++){
            for(int j=0;j<A.length-1-i;j++){
                if(A[j]>A[j+1]){
                    temp=A[j+1];
                    A[j+1]=A[j];
                    A[j]=temp;
                }
            }
        }
    }
}

选择排序:

public class Solution {
    /*
     * @param A: an integer array
     * @return: 
     */
    public void sortIntegers(int[] A) {
        // write your code here
        for(int i=0;i<A.length-1;i++){
            int min=A[i];
            int index=i;
            for(int j=i+1;j<=A.length-1;j++){
                if(A[j]<min){
                    min=A[j];
                    index=j;
                }
            }
            int b=A[i];
            A[i]=min;//把最小的值放在第i个;
            A[index]=b;
        }
    }
}




原创粉丝点击