Created
April 6, 2015 05:21
-
-
Save Leaking/646ca09224f2608862f9 to your computer and use it in GitHub Desktop.
Sort Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 冒泡排序 | |
* | |
* @param a | |
*/ | |
public static void bubbleSort(int[] a) { | |
int temp; | |
for (int i = 0; i < a.length; i++) | |
for (int j = 0; j < a.length - i - 1; j++) { | |
if (a[j] > a[j + 1]) { | |
temp = a[j]; | |
a[j] = a[j + 1]; | |
a[j + 1] = temp; | |
} | |
} | |
} | |
/** | |
* 改良的冒泡排序 | |
* | |
* @param a | |
*/ | |
public static void betterBubbleSort(int[] a) { | |
int temp; | |
boolean flag = false; | |
for (int i = 0; i < a.length; i++) { | |
for (int j = 0; j < a.length - i - 1; j++) { | |
if (a[j] > a[j + 1]) { | |
flag = true; | |
temp = a[j]; | |
a[j] = a[j + 1]; | |
a[j + 1] = temp; | |
} | |
} | |
if (flag == false) | |
return; | |
} | |
} | |
/** | |
* 选择排序 | |
* | |
* @param a | |
*/ | |
public static void selectionSort(int[] a) { | |
int temp, t; | |
for (int i = 0; i < a.length - 1; i++) { | |
temp = i; | |
for (int j = i + 1; j < a.length; j++) { | |
if (a[temp] > a[j]) | |
temp = j; | |
} | |
if (temp != i) { | |
t = a[temp]; | |
a[temp] = a[i]; | |
a[i] = t; | |
} | |
} | |
} | |
/** | |
* 快速排序 | |
* @param array | |
*/ | |
//快速排序 | |
public static void quick_sort(int s[], int l, int r) | |
{ | |
if (l < r) | |
{ | |
int i = l, j = r, x = s[l]; | |
while (i < j) | |
{ | |
while(i < j && s[j] >= x) // 从右向左找第一个小于x的数 | |
j--; | |
if(i < j) | |
s[i++] = s[j]; | |
while(i < j && s[i] < x) // 从左向右找第一个大于等于x的数 | |
i++; | |
if(i < j) | |
s[j--] = s[i]; | |
} | |
s[i] = x; | |
quick_sort(s, l, i - 1); // 递归调用 | |
quick_sort(s, i + 1, r); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment