码迷,mamicode.com
首页 > 其他好文 > 详细

Sort Integers

时间:2017-02-10 23:22:54      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:imp   select   open   tin   visible   bsp   process   swap   comm   

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

分析

bubble sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    /**
     * @param A an integer array
     * @return void
     */
    public void sortIntegers(int[] A) {
        // Write your code here
        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]) swap(A, j, j+1);
            }
        }
    }
     
    public void swap(int[] A, int i, int j){
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
}

selection sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    /**
     * @param A an integer array
     * @return void
     */
    public void sortIntegers(int[] A) {
        // Write your code here
        for(int i = 0; i < A.length; ++i){
            int min_i = i;
            for(int j = i; j < A.length; ++j){
                if(A[min_i] >= A[j])
                    min_i = j;
            }
            swap(A, i, min_i);
        }
    }
     
    public void swap(int[] A, int i, int j){
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
}

insert sort





Sort Integers

标签:imp   select   open   tin   visible   bsp   process   swap   comm   

原文地址:http://www.cnblogs.com/zhxshseu/p/8790b728cc7f1f47d2f5e216d82f9f2d.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!