一、冒泡
public class maopao {
public static void main(String[] args) {
int[] b={8,5,1,2};
//有N个数,只需要比较N-1趟,所以i<b.length-1,
for (int i = 0; i <b.length-1 ; i++) {
//每一趟比较的次数是比上一趟少一次
for (int k = 0; k <b.length-i-1 ; k++) {
if(b[k]<b[k+1]){
int a=b[k+1];
b[k+1]=b[k];
b[k]=a;
}
}
}
//
for (int j = 0; j < b.length; j++) {
System.out.println(b[j]+"\t");
}
}
}
二、快速
public class kuaisu01 {
public static void quickSort(int[] arr,int low,int high){
int i,j,temp,t;
if(low>high){
return;
}
i=low;
j=high;
//temp就是基准位
temp = arr[low];
while (i<j) {
//先看右边,依次往左递减
while (temp<=arr[j]&&i<j) {
j--;
}
//再看左边,依次往右递增
while (temp>=arr[i]&&i<j) {
i++;
}
//如果满足条件则交换
if (i<j) {
t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
//最后将基准为与i和j相等位置的数字交换
arr[low] = arr[i];
arr[i] = temp;
//递归调用左半数组
quickSort(arr, low, j-1);
//递归调用右半数组
quickSort(arr, j+1, high);
}
public static void main(String[] args){
int[] arr = {10,7,2,4,7,62,3,4,2,1,8,9,19};
quickSort(arr, 0, arr.length-1);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
三、折半(二分)
public class zheban {
public static void main(String[] args) {
zheban(105,new int[]{4,7,8,9,14,25,45,48});
}
public static int zheban(int b,int[] a) {
int low=0;
int high=a.length-1;
int mod=a.length/2;
while(low<high){
if(b==a[mod]){
System.out.println("所查找的数在第"+mod+"位");
return 0;
}
while(b<a[mod]&&low<high)
{
if(b==a[low]){
System.out.println("所查找的数在第"+low+"位");
return 0;
}
low++;
}
while(b>a[mod]&&low<high){
if(b==a[high]){
System.out.println("所查找的数在第"+high+"位");
return 0;
}
high--;
}
}
System.out.println("没这个数");
return 0;
}
}
四、直接插入
public class zhijiepaixu {
public static void main(String[] args) {
int[] a={8,4,75,15,24,3,56,15,21,58};
kuaisu(a);
for (int i = 0; i <a.length; i++) {
System.out.println(a[i]);
}
}
public static void kuaisu(int[] a){
for (int i = 1; i <a.length ; i++) {
if(a[i]<a[i-1]){//先找小于数组的数
//再找数组,找到插入的位置
int change=a[i];
int j=i-1;
while(change<a[j]){
//数组的位置往后移,
a[j+1]=a[j];
j--; //目的是再次比较数组和change的值
if(j<0){
break;
}
}
a[j+1]=change;
}
}
}
}