排序
冒泡排序
public class Sort01 {
public static void sort(int a[]) {
int n = a.length;
for (int i = n - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}
public static void main(String[] args) {
int[] a = {0, 3, 6, 8, 2, 4, 6, 9, 7, 5};
sort(a);
System.out.println(Arrays.toString(a));
}
}
选择排序
public class Sort02 {
public static void main(String[] args) {
int[] a = {2, 5, 5, 3, 9, 6, 1, 4, 8, 7};
selectSort(a);
System.out.println(Arrays.toString(a));
}
public static void selectSort(int[] array) {
//min用来保存数组中最小元素的索引值
for (int i = 0, len = array.length; i < len - 1; i++) {
int min=i;
for (int j = i + 1; j < len; j++)
if (array[j] < array[min])
min = j;
//每趟最多交换一次
if (min != i) //如果min不等于当前的i,让最小值的和当前位置的值交换
{
int temp = array[min];
array[min] = array[i];
array[i] = temp;
}
}
}
}
归并排序
public class Sort04 {
public static void main(String[] args) {
int[] data = new int[] { 5, 3, 6, 2, 1, 9, 4, 8, 7 };
mergeSort(data,0,data.length-1);
System.out.println(Arrays.toString(data));
}
public static void mergeSort(int[] data,int left,int right) {
if (left >= right) return;
int center = (left + right) / 2;
mergeSort(data, left, center);
mergeSort(data, center + 1, right);
merge(data, left, center, right);
}
public static void merge(int[] data, int left, int center, int right) {
int[] tmpArr = new int[data.length];
int mid = center + 1,third = left,tmp = left;
while (left <= center && mid <= right) {
if (data[left] <= data[mid]) tmpArr[third++] = data[left++];
else tmpArr[third++] = data[mid++];
}
while (mid <= right) tmpArr[third++] = data[mid++];
while (left <= center) tmpArr[third++] = data[left++];
while (tmp <= right) data[tmp] = tmpArr[tmp++];
}
}
基数排序
public class Sort05 {
public static void main(String[] args) {
int[] data = new int[] { 1100, 192, 221, 12, 23 };
radixSort(data, 10, 4);
System.out.println("排序后的数组:"+Arrays.toString(data));
}
public static void radixSort(int[] data, int radix, int d) {
int[] tmp = new int[data.length],buckets = new int[radix];
for (int i = 0, rate = 1; i < d; i++) {
Arrays.fill(buckets, 0);
System.arraycopy(data, 0, tmp, 0, data.length);
for (int j = 0; j < data.length; j++) {
int subKey = (tmp[j] / rate) % radix;
buckets[subKey]++;
}
for (int j = 1; j < radix; j++) buckets[j] = buckets[j] + buckets[j - 1];
for (int m = data.length - 1; m >= 0; m--) {
int subKey = (tmp[m] / rate) % radix;
data[--buckets[subKey]] = tmp[m];
}
rate *= radix;
}
}
}