1.冒泡法排序
//冒泡
public int[] bubble(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
return a;
}
2.简单选择排序
//选择
public int[] option(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
return a;
}
3.快速法排序
//快速
public int[] quickSort(int[] n, int left, int right) {
int dp;
if (left < right) {
/*
这就是下面要讲到的函数,按照上面所说的,就是把所有小于53的数放
到它的左边,大的放在右边,然后返回53在整理过的数组中的位置。
*/
dp = partition(n, left, right);
quickSort(n, left, dp - 1);
quickSort(n, dp + 1, right); //这两个就是递归调用,分别整理53左边的数组和右边的数组
}
return n;
}
public int partition(int n[], int left, int right) {
int lo, hi, pivot, t;
pivot = n[left];
lo = left - 1;
hi = right + 1;
while (lo + 1 != hi) {
if (n[lo + 1] <= pivot) {
lo++;
} else if (n[hi - 1] > pivot) {
hi--;
} else {
t = n[lo + 1];
n[++lo] = n[hi - 1];
n[--hi] = t;
}
}
n[left] = n[lo];
n[lo] = pivot;
return lo;
}
4.插入法排序
//插入
public int[] insertion(int[] a) {
for (int i = 1; i < a.length; i++) {
int p = i;
// int key = a[p];
while (p > 0 && a[p - 1] > a[p]) {
int t = a[p - 1];
a[p - 1] = a[p];
a[p] = t;
p--;
}
}
return a;
}
5.约瑟夫环
public int[] john(int[] a) {
int index = a.length;
int i = 0;
int count = 0;
int length = a.length;
int[] b = new int[a.length];
while (index >0) {
if (a[i] == 1) {
i = (i + 1) % length;
continue;
}
if (count == 3) {
a[i] = 1;
count = 0;
index--;
if (i == 0) {
System.out.println("i " + length);
} else {
System.out.println("i " + i);
}
}
count++;
i = (i + 1) % length;
}
return b;
}