/**
* Demonstrate various sorting methods
*/
Package com.test1;
Import java.util.*;
public class Demo5_3 {
public static void Main (string[] args) {
TODO auto-generated Method Stub
int len=8;
int arr1[]=new Int[len];
for (int i=0;i<len;i++)
{
Let the program randomly generate a 1-10000 number
Math.random () randomly generates a 0-1 number
int t= (int) (Math.random () *10000);
arr1[i]=t;
}
int arr[]={1,6,0,-1,9,4,34,2};
Create a Bubble class
Bubble bubble=new Bubble ();
Bubble.sort (arr);
Create a Select Class
Select Select=new Select ();
Bubble bubble=new Bubble ();
QuickSort qs=new QuickSort ();
Print the system time before sorting
Calendar cal=calendar.getinstance ();
System.out.println ("Pre-sort" +cal.gettime ());
Bubble.sort (ARR1);
Qs.sort (0, Arr1.length-1, arr1);
Get the instance back
Cal=calendar.getinstance ();
System.out.println ("Post-sorting" +cal.gettime ());
Insertsort insertsort=new Insertsort ();
Insertsort.sort (arr);
Results after sorting the output
for (int i=0;i<arr1.length;i++)
{
System.out.print (arr1[i]+ "");
}
}
}
Quick Sort
Class quicksort{
public void sort (int left,int right,int array[]) {
int l=left;
int r=right;
int pivot=array[(Left+right)/2];
int temp=0;
while (L<r) {
while (Array[l]<pivot) l++;
while (Array[r]>pivot) r--;
if (l>=r) break;
TEMP=ARRAY[L];
ARRAY[L]=ARRAY[R];
Array[r]=temp;
if (Array[l]==pivot)--r;
if (Array[r]==pivot) ++l;
}
if (l==r)
{
l++;
r--;
}
if (left<r) sort (left,r,array);
if (right>l) sort (l,right,array);
}
}
Insert Sort
Class Insertsort
{
public void sort (int arr[])
{
for (int i=1;i<arr.length;i++)
{
int insertval=arr[i];
Insertval preparation compared to the previous number
int index=i-1;
while (Index>=0&&insertval<arr[index])
{
Will move the arr[index] backwards
Arr[index+1]=arr[index];
index--;
}
Insert the insertval in the appropriate location
Arr[index+1]=insertval;
}
}
}
Class Select
{
Select sort
public void sort (int arr[])
{
int temp=0;
for (int j=0;j<arr.length-1;j++)
{
Think the first number is the smallest
int MIN=ARR[J];
Subscript for record minimum number
int minindex=j;
for (int k=j+1;k<arr.length;k++)
{
if (Min>arr[k])
{
Modify Minimum
MIN=ARR[K];
Minindex=k;
}
}
Exchange
TEMP=ARR[J];
Arr[j]=arr[minindex];
Arr[minindex]=temp;
}
}
}
Class bubble{
Sorting methods
public void sort (int arr[])
{
int temp=0;
Sort
Outer Loop, decided to walk a few times
for (int i=0;i<arr.length-1;i++)
{
The inner loop begins to compare one after another, and if a number is found after the previous number, the Exchange
for (int j=0;j<arr.length-1-i;j++)
{
if (arr[j]>arr[j+1])
{
Swap location
TEMP=ARR[J];
ARR[J]=ARR[J+1];
Arr[j+1]=temp;
}
}
}
}
}
Select Bubble Quick Insert Sort