Sort Integers
Posted copperface
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sort Integers相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
1356. Sort Integers by The Number of 1 Bits
[LintCode] Sort Integers II 整数排序之二
LeetCode --- 1356. Sort Integers by The Number of 1 Bits 解题报告
LeetCode | 1387. Sort Integers by The Power Value将整数按权重排序Python