463. 整数排序

Sort Integers

Description

Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n2) algorithm.

Example

Given [3, 2, 1, 4, 5], return [1, 2, 3, 4, 5].

插入排序

public class Solution {
    /**
     * @param A: an integer array
     * @return: nothing
     */
    public void sortIntegers(int[] A) {
         	int len = A.length;
    	int target;
    	
    	for(int i=1; i<len;i++) {
    		target = A[i];
    		int j = i;
    		while(j>0 && target < A[j-1]) {
    			A[j] = A[j-1];
    			j--;
    		}
    		A[j] = target;
    	}
        
    }
}


选择排序

/*        
for (int i=0; i<A.length-1; i++){
            for(int j=i+1;j<A.length; j++){
                if(A[i] > A[j]){
                    int temp = 0;
                    
                    temp = A[j];
                    A[j] = A[i];
                    A[i] = temp;
     
                }
            }     
        } */

冒泡排序

/*    	
for(int i=0;i<A.length-1;i++) {
    		for(int j=0;j<A.length-i-1;j++) {
    			if(A[j] > A[j+1]) {
    				int temp = A[j+1];
    				A[j+1] = A[j];
    				A[j] = temp;
    			}
    		}
    	}*/
    	
描述
给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。

您在真实的面试中是否遇到过这个题?  
样例
对于数组 [3, 2, 1, 4, 5], 排序后为:[1, 2, 3, 4, 5]。
posted @ 2019-04-02 22:48  故人叹  阅读(120)  评论(0)    收藏  举报