common sort

Sorting Concept:

 

1. Internal sorting:


 

 

Methods such as swapping array elements and generating data sources are defined in the tool class (for the following sorting):

import java.util.Random;

public class SortUtil {

	// swap element position by array subscript
	public static void swap(int[] data, int i, int j) {
		int temp = data[i];
		data[i] = data[j];
		data[j] = temp;
	}

	// Generate and display the data source
	public static void DataSrc(int[] is) {
		for (int i = 0; i < is.length; i++) {
			is[i] = new Random().nextInt(100);
		}
		System.out.print("Source data:\t");
		for (int i = 0; i < is.length; i++) {
			System.out.print(+is[i] + " ");
		}
		System.out.println();
	}

	// display the final sorting result
	public static void showRes(int[] is) {
		System.out.print("Sort result:\t");
		for (int i = 0; i < is.length; i++) {
			System.out.print(+is[i] + " ");
		}
	}

	// Display the situation after each sorting
	public static void showEach(int[] is, int i) {
		System.out.print("th" + (i + 1) + "order:\t");
		for (int k = 0; k < is.length; k++) {
			System.out.print(is[k] + " ");
		}
		System.out.println();
	}
}


 
        1.1 Bubble sort:

 

        The basic idea of ​​bubble sorting is to perform multiple scans of the keywords of the records to be sorted from back to front (reverse order). Swap, so that records with smaller keywords will gradually move from back to front, just like bubbles   float up in water, so this algorithm is also called bubble sort.

 

Bubble sort diagram:

 Code:

public class BubbleSort {

	public static void main(String[] args) {
		int[] is = new int[10];
		// Generate 10 random numbers within 100 as the data source in the tool class and display
		SortUtil.DataSrc (is);

		for (int i = 0; i < is.length - 1; i++) {
			for (int j = 0; j < is.length - i - 1; j++) {
				if (is[j] > is[j + 1]) {
					SortUtil.swap(is, j, j + 1);// Swap the two numbers by subscripting
				}
			}
			// display the result of each sorting
			SortUtil.showEach(is, i);
		}
		// display the final sorting result
		SortUtil.showRes (is);

	}

}

Sorting results and process: 

 

 

 

 

 

    1.2 Quick Sort:

        Quicksort uses a branching strategy to divide the sequence of sorted elements into two subsequences. The specific steps are:

        (1): Pick out an element from the sequence, which is called the "datum".

        (2): Scan the sequence once, and arrange all elements smaller than the "benchmark" in front of the benchmark, and all elements larger than the "benchmark" are arranged behind the "benchmark".

        (3): Divide each subsequence into smaller sequences through recursion, until the subsequences smaller than the "reference" element and the subsequences larger than the reference element are sorted.

 

Quick Complaint Steps:


 

 Quick sort implementation:

public class QuickSort {

	public static void main(String[] args) {
		int[] is = new int[10];
		SortUtil.DataSrc (is);
		quickSort(is, 0, is.length-1);
		SortUtil.showRes (is);
	}
	
	private static void quickSort(int[] data, int i, int j) {
		int pivotIndex = (i + j) / 2;
		SortUtil.swap (data, pivotIndex, j);

		int k = partition(data, i - 1, j, data[j]);
		SortUtil.swap (data, k, j);
		if ((k - i) > 1)
			quickSort(data, i, k - 1);
		if ((j - k) > 1)
			quickSort(data, k + 1, j);
	}

	private static int partition(int[] data, int l, int r, int pivot) {
		do {
			while (data[++l] < pivot)
				;
			while ((r != 0) && data[--r] > pivot)
				;
			SortUtil.swap (data, l, r);
		} while (l < r);
		SortUtil.swap (data, l, r);
		return l;
	}
}

 Quick sort results:

 

--------------------------------------------------------

 

 

 

 

 

        1.3 Simple selection sort:

                The basic idea of ​​selection sort: scan n records, select the smallest record, output it, then scan the remaining n-1 records, select the smallest record and output it, ... keep repeating this process until only one record remains.

Simple selection sort:

Simple selection sort implementation: 

public class SelectionSort {
	public static void main(String[] args) throws Exception {
		int[] is = new int[10];
		SortUtil.DataSrc (is);
		sort(is);
		SortUtil.showRes (is);
	}

	private static void sort(int[] is) {
		for (int i = 0; i < is.length - 1; i++) {
			for (int j = i + 1; j < is.length; j++) {
				if (is[i] > is[j]) {
					SortUtil.swap(is, i, j);
				}
			}
			SortUtil.showEach(is, i);
		}
	}
}

operation result:

 

 

 

 

 

 

 

 


   1.4 Heap Sort

                Heap sort is a complete binary tree, each node in the tree corresponds to a record of the original data, and each node should meet the following conditions: the data of the non-leaf node is greater than or equal to its left and right children

        Data (if it is sorted from small to large, the data of non-leaf nodes is required to be less than or equal to the data of its left and right child nodes).

        It can be seen from the definition of heap that its root node is the maximum value, and heap sorting is carried out by using this feature. The process of heap sorting includes two stages:

        (1): Construct unordered data into a heap (that is, use unordered data to generate a complete binary tree that satisfies the definition of heap).

        (2): Use heap sorting (use the heap generated in the previous step to generate ordered data, which is actually traversing the complete binary tree).

Example: 69,65,90,37,92,6,28,54:

The tree generation process:

 

Heap sorting output process (every time after a number is generated, the structure of the tree needs to be changed, and it needs to be regenerated):



 

Heap sort implementation: 

public class DeapSort {

	public static void main(String[] args) {
		int[] is = new int[10];
		SortUtil.DataSrc (is);
		sort(is);
		SortUtil.showRes (is);
	}

	public static void sort(int[] data) {
		MaxHeap h = new MaxHeap();
		h.init(data);
		for (int i = 0; i < data.length; i++)
			h.remove();
		System.arraycopy(h.queue, 1, data, 0, data.length);
	}

	private static class MaxHeap {
		private int size = 0;
		private int[] queue;

		void init(int[] data) {
			this.queue = new int[data.length + 1];
			for (int i = 0; i < data.length; i++) {
				queue[++size] = data[i];
				fixUp(size);
			}
		}

		public void remove() {
			SortUtil.swap (queue, 1, size--);
			fixDown(1);
		}

		// fixdown
		private void fixDown(int k) {
			int j;
			while ((j = k << 1) <= size) {
				if (j < size && queue[j] < queue[j + 1])
					j++;
				if (queue[k] > queue[j]) // no swap
					break;
				SortUtil.swap (queue, j, k);
				k = j;
			}
		}

		private void fixUp(int k) {
			while (k > 1) {
				int j = k >> 1;
				if (queue[j] > queue[k])
					break;
				SortUtil.swap (queue, j, k);
				k = j;
			}
		}
	}
}

  

 

 

 

 

 

 

 

           1.5 Direct Insertion Sort:

               The algorithm description of InsertionSort is a simple and intuitive sorting algorithm. Its working principle is to construct an ordered sequence, for unsorted data, scan from back to front in the sorted sequence, find the corresponding position and insert .In the implementation of insertion sort, in the process of scanning from back to front, it is necessary to repeatedly move the sorted elements backward step by step to provide insertion space for the latest element.

Direct insertion sort:

Direct insertion sort implementation:

public class InsertSort {

	public static void main(String[] args) {
		int[] is = new int[10];
		SortUtil.DataSrc (is);
		sort(is);
		SortUtil.showRes (is);
	}

	private static void sort(int[] is) {
		for (int i = 1; i < is.length; i++) {// By default, only one element is ordered, so no sorting is required
			for (int j = i; j > 0; j--) {
				if (is[j] < is[j - 1])
					SortUtil.swap(is, j, j - 1);
			}
		}
	}
}

 

 

 

 

 

 

 

 

         1.6 Hill sort:

            Hill sorting, also known as shrinking incremental sorting, also belongs to the insertion sorting algorithm, which is an improvement on direct insertion sorting.

The basic idea is to divide the sequence that needs to be sorted into several smaller sequences, and perform direct insertion sorting on these sequences. Through this operation, the sequence to be sorted can be basically ordered, and finally use the direct insertion sorting again. In this way, The efficiency can be improved by performing direct insertion sorting on a small number of sequences first, and finally by direct insertion sorting on basically ordered sequences, which can also improve the efficiency, and the efficiency of the sorting process is improved.

Diagram of Hill sorting process:


 Hill sort implementation:

public class ShellSort {

	public static void main(String[] args) {
		int[] is = new int[10];
		SortUtil.DataSrc (is);
		sort(is);
		SortUtil.showRes (is);
	}

	public static void sort(int[] data) {
		for (int i = data.length / 2; i > 2; i /= 2) {
			for (int j = 0; j < i; j++) {
				insertSort(data, j, i);
			}
		}
		insertSort(data, 0, 1);
	}

	private static void insertSort(int[] data, int start, int inc) {
		for (int i = start + inc; i < data.length; i += inc) {
			for (int j = i; (j >= inc) && (data[j] < data[j - inc]); j -= inc) {
				SortUtil.swap (data, j, j - inc);
			}
		}
	}
}

 

 

 

 

 

 

 

 

        1.7 Merge Sort (MergeSort):

                It is to combine two or more sorted lists into one sorted list.

Merge sort diagram:

 Merge sort implementation:

public class MergeSort {

	public static void main(String[] args) {
		int[] is = new int[10];
		SortUtil.DataSrc (is);
		sort(is);
		SortUtil.showRes (is);
	}

	public static void sort(int[] data) {
		int[] temp = new int[data.length];
		mergeSort(data, temp, 0, data.length - 1);
	}

	private static void mergeSort(int[] data, int[] temp, int l, int r) {
		int mid = (l + r) / 2;
		if (l == r)
			return;
		mergeSort(data, temp, l, mid);
		mergeSort(data, temp, mid + 1, r);

		for (int i = l; i <= r; i++) {
			temp[i] = data[i];
		}
		int i1 = l;
		int i2 = mid + 1;
		for (int cur = l; cur <= r; cur++) {
			if (i1 == mid + 1)
				data[cur] = temp[i2++];
			else if (i2 > r)
				data[cur] = temp[i1++];
			else if (temp[i1] < temp[i2])
				data[cur] = temp[i1++];
			else

				data[cur] = temp[i2++];
		}
	}
}

 

 

 

 

 

 

2. External sorting:

       External sorting refers to the sorting of large files. When the file to be sorted is large, all records of the entire file cannot be transferred into the memory for sorting at the same time, and the files can only be stored in external storage. This sorting is called external sorting. The process of external sorting is mainly based on the combination of internal and external memory exchange of data and "internal merge".

Generally speaking, sorting refers to internal sorting, such as quick sort, heap sort, merge sort, etc. The so-called internal sorting is a sorting that can be done in memory. The access speed of RAM is about 250,000 times that of disk, and we certainly hope that if we can, it is all done in-line. But for large data sets, the memory is far from enough, and the knowledge of external sorting is involved at this time.
The most commonly used algorithm for external sorting is multi-way merge sorting, that is, the original file is divided into multiple parts that can be loaded into memory at one time, and each part is loaded into memory to complete the sorting. Then, merge-sort the already sorted subfiles.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326565416&siteId=291194637
Recommended