464.Sort Integers II-整数排序 II(容易题)
来源:互联网 发布:淘宝网店打底衫长袖 编辑:程序博客网 时间:2024/05/24 06:09
整数排序 II
题目
给一组整数,按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。
样例
给出 [3, 2, 1, 4, 5], 排序后的结果为 [1, 2, 3, 4, 5]。
题解
1.快速排序
public class Solution { /** * @param A an integer array * @return void */ public void sortIntegers2(int[] A) { quickSort(A, 0, A.length - 1); } private void quickSort(int[] a, int left, int right) { if (left < right) { int temp = a[left]; int i = left; int j = right; while (i < j) { while (j >i && a[j] >= temp) { j--; } while (i < j && a[i] <= temp) { i++; } if (i < j) { swap(a, i, j); } } swap(a, left, j); quickSort(a,left,i-1); quickSort(a, i+1, right); } }}
2.归并排序
public class Solution { /** * @param A an integer array * @return void */ public void sortIntegers2(int[] A) { mergeSort(A, 0, A.length - 1); } private void mergeSort(int[] a, int low, int hi) { if (low < hi) { int mid = (low + hi) / 2; mergeSort(a, low, mid); mergeSort(a, mid + 1, hi); mergeArray(a, low, mid, hi); } } private void mergeArray(int[] a, int low, int mid, int hi) { if (low > mid) { return; } int[] temp = new int[hi - low + 1]; int i = low; int j = mid + 1; int k = 0; while (i <= mid && j <= hi) { temp[k++] = a[i] < a[j] ? a[i++] : a[j++]; } while (i <= mid) { temp[k++] = a[i++]; } while (j <= hi) { temp[k++] = a[j++]; } for (int k2 = 0; k2 < temp.length; k2++) { a[low + k2] = temp[k2]; } }}
3.堆排序
public class Solution { /** * @param A an integer array * @return void */ public void sortIntegers2(int[] A) { heapSort(A,A.length); } private void heapSort(int[] a, int n) { //建立最大堆 for (int i = n/2 - 1;i >= 0;i--) { minHeapAdjust(a, i, n); } //排序 for (int i = n - 1; i >= 1; i--) { swap(a, i, 0); minHeapAdjust(a, 0, i); } } private void minHeapAdjust(int[] a, int i, int n) { int j,tmp; tmp = a[i]; j = 2 * i + 1; while (j < n) { if (j + 1 < n && a[j+1] > a[j]) { j++; } if (a[j] < tmp) { break; } a[i] = a[j]; i = j; j = 2 * i + 1; } a[i] = tmp; } private void swap(int[] a, int i, int j) { int temp = a[j]; a[j] = a[i]; a[i] = temp; }
Last Update 2016.9.18
0 0
- 464.Sort Integers II-整数排序II(容易题)
- 464.Sort Integers II-整数排序 II(容易题)
- #464 Sort Integers II
- 464.整数排序 II
- 464. 整数排序 II
- 463.Sort Integers-整数排序(入门题)
- [LintCode] Sort Integers 整数排序
- 64.Merge Sorted Array II-合并排序数组 II(容易题)
- 【LintCode】整数排序II
- 整数排序II-lintcode
- lintcode_整数排序 II
- LintCode-整数排序 II
- 整数排序 II
- 整数排序 II
- 整数排序 II
- 整数排序 II
- 整数排序 II
- 整数排序 II
- 数据结构——顺序表
- 实验二.任务二.标准体重计算器
- GUI编程
- hdu 1992-Tiling a Grid With Dominoes
- hdu 5889 Barricade 2016ACM/ICPC青岛赛区网络赛1011
- 464.Sort Integers II-整数排序 II(容易题)
- 用Java实现简单的数据库连接池
- 数据结构——单链表的操作
- leetcode Longest Palindromic Substring(C)
- BaseAdaPeter<笔记>
- 阿里云服务器磁盘空间不足解决办法
- 利用 ICMP 隧道穿透防火墙
- 469.Identical Binary Tree-等价二叉树(容易题)
- 堆栈