Algorithm basics-Java and Python implementation of the eight classical sorting algorithms

Source: Internet
Author: User

Algorithm basics-Java and Python implementation of the eight classical sorting algorithms
There is no need to talk about the eight sorting algorithms. The programmer's algorithm basics must be mastered. Now Let's sum up to deepen the memory. Is the classification, name, temporal complexity, and stability of these eight sorting algorithms. The following code is the Java and Python code of the eight classical sorting algorithms. It is implemented based on the pseudocode in the introduction to algorithms in the classical algorithm book. I have attached a comment to the key statement section. The implementation (ascending) of the eight sorting algorithms is introduced in the order in which Java is used and Python is followed. Java's sorting function is written in a class, and Python's sorting function is written directly. Insert sort directly

Public class InsertSort {// insert sorting, preferably O (n), worst case O (n ^ 2), stable original address sorting public int [] Sort (int [] arr) {for (int I = 0; I = 0 & arr [j]> key; j --) arr [j + 1] = arr [j]; // note! This is not an exchange. Instead, we move all those greater than the key back to arr [j + 1] = key; // key and insert the appropriate position} return arr ;}}
Def insertSort (arr): # insert sorting. The worst is O (n ^ 2), and the best is O (n) # Sort an array in ascending order, change the while statement to arr [I] in descending order.
 
  
= 0 and arr [I]> key): # compare the number and current number to be inserted from the back to the front, the arr [J-1], arr [J-2]... move to the right until you find the appropriate location of arr [j]. arr [I + 1] = arr [I] I-= 1 arr [I + 1] = key [j] insert to this position return arr
 
Hill sorting
Public class ShellSort {// Hill sorting, preferably O (n), worst case O (n ^ 2), and average is better than direct insertion sorting, the average condition is O (n ^ 1.3) // unstable. The original order is public int [] Sort (int [] arr) {int n = arr. length; for (int gap = n; gap> 0; gap/= 2) {for (int I = gap; I <n; I ++) {if (arr [I] <arr [I-gap]) {// if it is smaller than the preceding element, int key = arr [I]; int j = I-gap; while (j> = 0 & arr [j]> key) {arr [j + gap] = arr [j]; j-= gap;} arr [j + gap] = key ;}} return arr ;}}
Def shellSort (arr): # insert sorting for simplified version-hill sorting. The worst is O (n ^ 2), the best is O (n), and the average is O (n ^ 1.3) gap = len (arr)/2 while gap> 0: for I in range (gap, len (arr): if arr [I] <arr [I-gap]: # The following elements are smaller than the preceding ones. Use gap as the step to insert the sort key = arr [I] j = I-gap while j> = 0 and arr [j]> key: arr [j + gap] = arr [j] j-= gap arr [j + gap] = key # step size minus half gap/= 2 return arr
Select sort directly
Public class SelectSort {// select sorting. The worst and best values are O (n ^ 2), which is unstable. The original sorting is public int [] Sort (int [] arr) {int n = arr. length; if (n <2) return arr; for (int I = 0; I
 
  
Def selectSort (arr): # select sorting, the worst is O (n ^ 2) # Sort an array in ascending order, and change the while statement to arr [I] in descending order.
   
    
Heap sorting
    
Public class HeapSort {// maintain a maximum heap so that it uses the element of the I node as the root public void maxHeapify (int [] arr, int I, int heap_size) {int l = 2 * I + 1; // The left child node int r = l + 1; int largest = I; if (l
     
      
Arr [largest]) largest = l; if (r
      
       
Arr [largest]) largest = r; if (largest! = I) {// ensure that the I node is the largest, and maintain the maximum heap int tmp = arr [I]; arr [I] = arr [largest]; arr [largest] = tmp; maxHeapify (arr, largest, heap_size) ;}} public void buildMaxHeap (int [] arr) {int heap_size = arr. length; int mid = (heap_size-1)/2; // create arr as the maximum heap from the intermediate node (just traverse half of the array ), finally, make arr [0] the root of the largest heap for (int I = mid; I> = 0; I --) maxHeapify (arr, I, heap_size );} public int [] Sort (int [] arr) {// first build the array as the maximum heap buildMaxHeap (arr); // traverse from the back to the front, arr [0] maximum for (int I = arr. length-1; I> = 0; I --) {int tmp = arr [0]; arr [0] = arr [I]; arr [I] = tmp; int heap_size = I; maxHeapify (arr, 0, heap_size);} return arr ;}}
      
     
Def maxHeapify (arr, I, heap_size): # maintain a maximum heap and reduce the value of arr [I] in the maximum heap step by step, the subtree that makes I the root node the largest heap. O (lgn) l = 2 * I + 1 # subscript I starts from 0, therefore, the subscript of the left child node is 2 * I + 1 r = l + 1 # largest = I if l
     
      
Arr [largest]: # note that heap_size is initialized to len (arr). Here, it is determined that it should be l
      
       
Arr [largest]: largest = r if largest! = I: # If I is not the root node of the largest heap, it will exchange values and make largest the subtree of the root node to keep the largest heap arr [largest], arr [I] = arr [I], arr [largest] maxHeapify (arr, largest, heap_size) def buildMaxHeap (arr): # top-up, convert arr to Max heap_size = len (arr) mid = int (heap_size-1)/2) for I in range (mid,-1,-1): maxHeapify (arr, i, heap_size) def heapSort (arr): buildMaxHeap (arr) # time complexity O (n) size = len (arr) # n-1 calls to maxHeapify, time complexity O (nlgn) for I in range (size-1,-1,-1): arr [I], arr [0] = arr [0], arr [I] # store from the back to the back. According to the maximum heap nature, arr [0] is the maximum heap_size of the current maximum heap = I maxHeapify (arr, 0, heap_size)
      
     

Bubble Sorting
public class PopSort {public int[] Sort(int[] arr) {int n = arr.length;if(n<2)return arr;for(int i=0;i
 
  i;j--){if(arr[j-1]>arr[j]){int tmp = arr[j];arr[j] = arr[j-1];arr[j-1] = tmp;}}return arr;}}
 
def popSort(arr):    n = len(arr)    if n < 2:        return arr        for i in range(n):        for j in range(n-1,i,-1):            if arr[j-1] > arr[j]:                arr[j-1],arr[j] = arr[j],arr[j-1]    return arr
Quick sorting
Public class QuickSort {public int getPartition (int [] arr, int low, int high) {int tmp; int index = low-1; for (int I = low; I
 
  
Def quickSort (arr, low, high): # quickly sort benchmark elements randomly to achieve the expected time complexity O (nlgn) # note that high is the maximum subscript if low Merge Sorting
  
Public class MergeSort {public void Sort (int [] arr, int low, int high) {if (low
   
    
Def mergeSort (arr, p, r): # p17, Merge Sorting, O (nlgn). Note that r is the maximum subscript of the array if p
     
      
It is too difficult to write the base sorting in Java, and a variety of troublesome ArrayList operations ~~ Therefore, only the Python version is pasted.
     
Def cntDigit (arr, radix): # obtain the maximum number of digits of an array element maxnum = arr [0] for x in arr: if x> maxnum: maxnum = x cnt = 0 while (maxnum! = 0): maxnum/= radix cnt + = 1 return cntdef radixSort (arr, radix = 10): k = cntDigit (arr, radix) # Get the maximum number of BITs bucket = [[] for I in range (radix)] for I in range (1, k + 1): for j in arr: # bucket [x] stores the number of I-bits x from low to high, such as 543 in the array, when I = 1, the bucket [j/(radix ** (I-1) % (radix)] In bucket [3] exists. append (j) del arr [:] # initialize arr # print (bucket) for z in bucket: # The array of the current number of digits is placed in arr in order. arr + = z del z [:] return arr

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.