冒泡,选择,快速,插入
1.冒泡
public class BubbleSort2 {
public static void main(String[] args) {
int[] arr={43,45,12,87,897};
for (int i = 0; i <arr.length-1 ; i++) {
for (int j = 0; j <arr.length-1-i ; j++) {
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for (int data:
arr) {
System.out.print(data+"\t");
}
}
}
2.选择
public class SelectSort1 {
public static void main(String[] args) {
int[] arr={10,2,43,1,4};
for (int i = 0; i <arr.length-1 ; i++) {
for (int j =i+1; j <arr.length ; j++) {
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for (int data:
arr) {
System.out.print(data+"\t");
}
}
}
3.快速排序
public class quickSort3 {
public static void main(String[] args) {
int[] arr={10,312,32,43,12};
quickSort(arr,0,arr.length-1);
for (int data:
arr) {
System.out.print(data+"\t");
}
}
public static void quickSort(int[] arr,int start,int end){
if(start<end){
int index=getIndex(arr,start,end);
quickSort(arr,start,index-1);
quickSort(arr,index+1,end);
}
}
private static int getIndex(int[] arr, int start, int end) {
int i=start;
int j=end;
int x=arr[i];
while (i<j)
{
while (i<j&&arr[j]>=x)
{
j--;
}
if(i<j){
arr[i]=arr[j];
i++;
}
while (i<j&&arr[i]<x){
i++;
}
if(i<j){
arr[j]=arr[i];
j--;
}
}
arr[i]=x;
return i;
}
}
4.插入排序
public class StraightInsert1 {
public static void main(String[] args) {
int arr[]={112,43,21,65,78};
for (int i = 1; i <arr.length ; i++) {
int j=i;
while (j>0&&arr[j-1]>arr[j])
{
int temp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
j--;
}
}
for (int data:
arr) {
System.out.print(data+"\t");
}
}
}