- 选择排序
public static void selectSort(int []a){
int i,j;
int temp=0,flag=0;
int n=a.length;
for(i=0;i<n;i++){
temp=a[i];
flag=i;
for(j=i+1;j<n;j++){
if(a[j]<temp){
temp=a[j];
flag=j;
}
}
if(flag!=i){
a[flag]=a[i];
a[i]=temp;
}
}
- 插入排序
public static void insertSort(int []a) {
if(a!=null){
for(int i=1;i<a.length;i++){
int temp=a[i],j=i;
if(a[j-1]>temp){
while(j>=1&&a[j-1]>temp){
a[j]=a[j-1];
j--;
}
}
a[j]=temp;
}
}
}
- 冒泡排序
public static void bubbleSort(int []a){
int temp;
for (int i=0;i<a.length-1;i++){
for(int j=i;j<a.length-2;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
- 快速排序(重要 )
参考文章链接:https://blog.csdn.net/v123411739/article/details/80071521
注意:当初始的序列整体或局部有序时,快速排序的性能将会下降
package com.spc.algorithm;
public class QuickSort {
public static void sort(int[] array, int low, int high) {
int i, j;
int index;
if (low > high)
return;
i = low;
j = high;
index = array[i];
while (i < j) {
while (i < j && array[j] > index) {
j--;
}
if (i < j) {
array[i++] = array[j];
}
while (i < j && array[i] < index) {
i++;
}
if (i < j) {
array[j--] = array[i];
}
}
array[i] = index;
sort(array, low, i - 1);
sort(array, i + 1, high);
}
public static void quicksort(int[] array) {
sort(array, 0, array.length - 1);
}
public static void main(String[] args) {
int i=0;
int a[]={5,4,9,8,7,6,0,1,3,2};
int len=a.length;
quicksort(a);
for(i=0;i<len;i++){
System.out.println(a[i]);
}
}
}
- 二分查找
package com.ls.binarysearch;
import java.util.Arrays;
import java.util.Scanner;
public class TestBinarySearch {
public static void main(String[] args){
int[] array ={80, 53, 63, 5, 81, 84, 88, 91, 94};
Arrays.sort(array);
System.out.println("查找的值:");
int t = new Scanner(System.in).nextInt();
int i = binarySearch(array, t);
System.out.println(i);
}
private static int binarySearch(int[] array, int t){
int lo = 0,mid,hi= array.length-1;
while (lo<=hi){
mid=(lo+hi)/2;
if(array[mid]<t){
lo=mid+1;
}else if (array[mid]>t){
hi=mid-1;
}else {
return mid;
}
}
return -1;
}
}