Skip to content

Instantly share code, notes, and snippets.

@jp1017
Forked from Leaking/Sort Algorithm
Created January 7, 2016 07:27
Show Gist options
  • Save jp1017/d4afc983ef55d66f4c79 to your computer and use it in GitHub Desktop.
Save jp1017/d4afc983ef55d66f4c79 to your computer and use it in GitHub Desktop.
Sort Algorithm
/**
* 冒泡排序
*
* @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