## 编程知识 cdmana.com

### Implementation of various sorting algorithms in Java

1. Direct insert sort

This sort of sorting problem is often encountered ： Insert the new data into the already arranged data column .

1. Sort the first number and the second number , And then form an ordered sequence
2. Insert the third number in , Form a new ordered sequence .
3. For the fourth number 、 The fifth number …… Until the last number , Repeat step 2 .

How to write code ：

1. First set the number of inserts , The number of cycles ,for(int i=1;i<length;i++),1 No need to insert the number .
2. Set the number of inserts and the number of digits to get the last number of the ordered sequence .insertNum and j=i-1.
3. Cycle forward from the last number , If the number of inserts is less than the current number , Just move the current number back one bit .
4. Put the current number in an empty position , namely j+1.

The code implementation is as follows ：

public void insertSort(int[] a){
int length=a.length;// The length of the array , This is extracted to speed up .
int insertNum;// The number to insert
for(int i=1;i<length;i++){// Number of inserts
insertNum=a[i];// The number to insert
int j=i-1;// The number of ordered sequence elements
while(j>=0&&a[j]>insertNum){// The sequence circulates from back to front , Will be bigger than the insertNum Move the number back one space
a[j+1]=a[j];// Element moves one space
j--;
}
a[j+1]=insertNum;// Put the number to be inserted in the position to be inserted .
}
}

2. Shell Sort

For the direct insertion sort problem , When the amount of data is huge .

1. Set the number of numbers to n, Take an odd number k=n/2, The difference between subscripts is k The books are divided into a group , Constitute an ordered sequence .
2. Retake k=k/2 , The difference between subscripts is k The books are divided into a group , Constitute an ordered sequence .
3. Repeat step 2 , until k=1 Perform simple insert sort .

How to write code ：

1. First determine the number of components .
2. Then insert and sort the elements in the group .
3. And then length/2, repeat 1,2 Step , until length=0 until .

The code implementation is as follows ：

public  void sheelSort(int[] a){
int d  = a.length;
while (d!=0) {
d=d/2;
for (int x = 0; x < d; x++) {// Number of components
for (int i = x + d; i < a.length; i += d) {// Elements in groups , Start with the second number
int j = i - d;//j The last digit of an ordered sequence
int temp = a[i];// Elements to insert
for (; j >= 0 && temp < a[j]; j -= d) {// Go back and forth .
a[j + d] = a[j];// Move backward d position
}
a[j + d] = temp;
}
}
}
}

3. Simple selection sort

It is often used to take the maximum and minimum number in a sequence .

( If every comparison is exchanged , So it's exchange ordering ; If you compare one cycle at a time and then exchange , It's a simple selection and sorting .)

1. Traverse the entire sequence , Put the minimum number first .
2. Traverse the rest of the sequence , Put the minimum number first .
3. Repeat step 2 , Until there is only one number left .

How to write code ：

1. First determine the number of cycles , And remember the current number and position .
2. Compare all the numbers after the current position with the current number , The decimal is assigned to key, And remember the decimal place .
3. After the comparison , Exchange the minimum value with the value of the first number .
4. repeat 2、3 Step .

The code implementation is as follows ：

public void selectSort(int[] a) {
int length = a.length;
for (int i = 0; i < length; i++) {// cycles
int key = a[i];
int position=i;
for (int j = i + 1; j < length; j++) {// Select the minimum value and position
if (a[j] < key) {
key = a[j];
position = j;
}
}
a[position]=a[i];// Swap places
a[i]=key;
}
}

4. Heap sort

Optimization of simple selection and sorting .

1. Build the sequence into a big top heap .
2. Exchange the root node with the last node , Then disconnect the last node .
3. Repeat first 、 Two steps , Until all nodes are disconnected .

The code implementation is as follows ：

public  void heapSort(int[] a){
System.out.println(" Start sorting ");
int arrayLength=a.length;
// Cycle building
for(int i=0;i<arrayLength-1;i++){
// Building the heap

buildMaxHeap(a,arrayLength-1-i);
// Swap top and last elements
swap(a,0,arrayLength-1-i);
System.out.println(Arrays.toString(a));
}
}
private  void swap(int[] data, int i, int j) {
// TODO Auto-generated method stub
int tmp=data[i];
data[i]=data[j];
data[j]=tmp;
}
// Yes data Array from 0 To lastIndex Build a large top pile
private void buildMaxHeap(int[] data, int lastIndex) {
// TODO Auto-generated method stub
// from lastIndex Nodes （ The last node ） Start of parent node of
for(int i=(lastIndex-1)/2;i>=0;i--){
//k Save the node being judged
int k=i;
// If at present k Child node of node exists
while(k*2+1<=lastIndex){
//k Index of the left child of the node
int biggerIndex=2*k+1;
// If biggerIndex Less than lastIndex, namely biggerIndex+1 Representative k The right child of the node exists
if(biggerIndex<lastIndex){
// If the value of the right child node is large
if(data[biggerIndex]<data[biggerIndex+1]){
//biggerIndex Always record the index of the larger child node
biggerIndex++;
}
}
// If k The value of a node is less than the value of its larger child nodes
if(data[k]<data[biggerIndex]){
// Exchange them
swap(data,k,biggerIndex);
// take biggerIndex give k, Start while Next cycle of the cycle , Reassurance k The value of a node is greater than the value of its left and right child nodes
k=biggerIndex;
}else{
break;
}
}
}
}

5. Bubble sort

Generally do not use .

1. Compare all elements of the sequence in pairs , Put the biggest one at the back .
2. Compare all elements of the remaining sequence in pairs , Put the biggest one at the back .
3. Repeat step 2 , Until there is only one number left .

How to write code ：

1. Set the number of cycles .
2. Set the number of digits to start the comparison , And the number of digits at the end .
3. Comparing the two , Put the smallest in front .
4. repeat 2、3 Step , Until the number of cycles is over .

The code implementation is as follows ：

public void bubbleSort(int[] a){
int length=a.length;
int temp;
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length-i-1;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}

6. Quick sort

Ask for the fastest time .

1. Choose the first number as p, Less than p The number of is on the left , Greater than p The number of is on the right .
2. Recursively will p The numbers on the left and right follow the first step , Until you can't recurse .

The code implementation is as follows ：

public static void quickSort(int[] numbers, int start, int end) {
if (start < end) {
int base = numbers[start]; //  Selected reference value （ The first value is the reference value ）
int temp; //  Record temporary intermediate value
int i = start, j = end;
do {
while ((numbers[i] < base) && (i < end))
i++;
while ((numbers[j] > base) && (j > start))
j--;
if (i <= j) {
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
i++;
j--;
}
} while (i <= j);
if (start < j)
quickSort(numbers, start, j);
if (end > i)
quickSort(numbers, i, end);
}
}

7. Merge sort

Second only to fast platoon , Use when memory is low , Can be used when parallel computing .

1. Choose two adjacent numbers to form an ordered sequence .
2. Select two adjacent ordered sequences to form an ordered sequence .
3. Repeat step 2 , Until it all forms an ordered sequence .

The code implementation is as follows ：

public static void mergeSort(int[] numbers, int left, int right) {
int t = 1;//  Number of elements in each group
int size = right - left + 1;
while (t < size) {
int s = t;//  The number of elements in each group of this cycle
t = 2 * s;
int i = left;
while (i + (t - 1) < size) {
merge(numbers, i, i + (s - 1), i + (t - 1));
i += t;
}
if (i + (s - 1) < right)
merge(numbers, i, i + (s - 1), right);
}
}
private static void merge(int[] data, int p, int q, int r) {
int[] B = new int[data.length];
int s = p;
int t = q + 1;
int k = p;
while (s <= q && t <= r) {
if (data[s] <= data[t]) {
B[k] = data[s];
s++;
} else {
B[k] = data[t];
t++;
}
k++;
}
if (s == q + 1)
B[k++] = data[t++];
else
B[k++] = data[s++];
for (int i = p; i <= r; i++)
data[i] = B[i];
}

For a large number of , When a long number is sorted .

1. Take out the single digits of all numbers , Sort by single digits , Make a sequence .
2. Take out the tens of all the new numbers , Sort by tens , Make a sequence .

The code implementation is as follows ：

public void sort(int[] array) {
// First, determine the number of times to sort ;
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
int time = 0;
// Determine the number of digits ;
while (max > 0) {
max /= 10;
time++;
}
// establish 10 A queue ;
List<ArrayList> queue = new ArrayList<ArrayList>();
for (int i = 0; i < 10; i++) {
ArrayList<Integer> queue1 = new ArrayList<Integer>();
}
// Conduct time Sub distribution and collection ;
for (int i = 0; i < time; i++) {
// Assign array elements ;
for (int j = 0; j < array.length; j++) {
// Get the number time+1 digit ;
int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
ArrayList<Integer> queue2 = queue.get(x);
queue.set(x, queue2);
}
int count = 0;// Element counter ;
// Collect queue elements ;
for (int k = 0; k < 10; k++) {
while (queue.get(k).size() > 0) {
ArrayList<Integer> queue3 = queue.get(k);
array[count] = queue3.get(0);
queue3.remove(0);
count++;
}
}
}
}

Based on my many years of working experience and learning experience , Recorded a new set of Java Focus on video tutorials , If you are learning now Java, At the beginning of learning Java There is no systematic learning course in the process , You can add groups 654631948 Collect the learning materials , Interview questions , Development tools, etc , There are senior people in the group java The teacher answers questions , Every day, there will also be live lectures on the basic part and architecture , You can also add my wechat renlliang2013 In depth communication , As long as I really want to learn Java People welcome .

java Basic course ：https://ke.qq.com/course/149432?tuin=57912c43

Java Distributed Internet Architecture / Microservices / High performance /springboot/springcloud：

https://ke.qq.com/course/179440?tuin=57912c43

Scroll to Top