一、交换排序
//冒泡排序
static void sort_bubble(int[] a) {
int temp=0;
for(int i=0;i<a.Length-1;i++){
for(int j=i+1;j<a.Length;j++){
if(a[i]>a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
//快速排序
static int sourtUnit(int[] array, int low, int hight)
{
int key = array[low];
while (low < hight)
{
while (low < hight && array[hight] > key)
hight--;
array[low] = array[hight];
while (low < hight && array[low] < key)
low++;
array[hight] = array[low];
}
array[low] = key;
return low;
}
static void sort(int[] array, int low, int hight)
{
if (low < hight)
{
//print(array);
int index = sourtUnit(array, low, hight);
sort(array, low, index - 1);
sort(array, index + 1, hight);
}
}
二、选择排序
//选择排序
static void sort_choice(int[] a) {
int index = 0,temp=0;
for (int i = 0; i < a.Length - 1; i++) {
index = i;
for (int j = i + 1; j < a.Length; j++)
{
if (a[index] > a[j]) index = j;
}
if (index != i)
{
temp = a[i];
a[i] = a[index];
a[index] = temp;
}
// print(a);
}
}
//堆排序
static void InitHeap(int[] a, int index,int length) {
int left = 2 * index + 1;
int right = 2 * index + 2;
int max=index;
if (index < length / 2)
{
if (left < length && a[max] < a[left])
max = left;
if (right < length && a[max] < a[right])
max = right;
if (max != index) {
int temp = a[index];
a[index] = a[max];
a[max] = temp;
InitHeap(a, max,length);
}
}
}
//
int[] c = getArray(100);
print(c);
for (int i = c.Length / 2 - 1; i >= 0; i--) {
InitHeap(c, i,c.Length);
}
//然后倒序交换
for (int i = c.Length - 1; i >= 0; i--)
{
int temp = c[0];
c[0] = c[i];
c[i] = temp;
InitHeap(c, 0, i);
}
print(c);
三、插入排序
//直接插入排序
static void sort_insert(int[] a) {
int index = 0, temp = 0;
for (int i = 1; i < a.Length; i++) {
index = i;
temp = a[i];
while (index > 0 && a[index - 1] > temp) {
a[index] = a[index - 1];
index--;
}
a[index] = temp;
}
}
//希尔排序
static void sort_shell_insert(int[] a)
{
int length = a.Length;
int interval = length / 2;
while (interval != 0)
{
for (int i = interval; i < length; i++)
{
int t = a[i];
int j = i - interval;
while (j >= 0 && t < a[j])
{
a[j + interval] = a[j];
j = j - interval;
}
a[j + interval] = t;
}
interval /= 2;
}
}
四、基数排序
public static void baseSort(int[] a,int d){
//创建一个二维数组
int [][]temp=new int[10][a.length];
int[] length=new int[a.length];
//循环次数
int div=1;//除数
int m=0;//控制循环次数
int k=0;//赋值的时候变量
//d循环次数最大数的位数
while(m<d){
for(int i=0;i<a.length;i++){
int lsd=(a[i]/div)%10;
temp[lsd][length[lsd]]=a[i];
length[lsd]++;
}
for(int i=0;i<10;i++){
if(length[i]!=0){
for(int j=0;j<length[i];j++)
a[k++]=temp[i][j];
}
length[i]=0;
}
System.out.println(Arrays.toString(a));
m++;
div*=10;
k=0;
}
}