Eight Sorting Algorithms for Data Structure

Keywords: less shell

I. Bubble Sorting

Thought: Repeat visits to the sequence to be sorted, compare two elements at a time, exchange them if their order is wrong, the smallest one comes up, followed by the second smallest.

Time complexity: O(n^2)

Spatial complexity: O(1)

Stability: Stability

1.

  1. /** 
  2.      * Bubble sort 
  3.      * @param disOrderArray 
  4.      * @return 
  5.      */  
  6.     public static int[] BubbleSort(int[] disOrderArray) {  
  7.         int temp;  
  8.         //Layer 1 loop: Indicates the number of comparisons, such as length elements, and the number of comparisons is length-1.  
  9.         for(int i=0;i<disOrderArray.length-1;i++)  
  10.         {  
  11.             //Exchange the smallest number with the relative top of the bubbles, the smallest one coming up at a time, and the second smallest.  
  12.             for(int j=disOrderArray.length-1;j>i;j–)  
  13.             {  
  14.                 //Here is < when it returns from small to large, and > when it returns from large to small.  
  15.                 if(disOrderArray[j] < disOrderArray[j-1])  
  16.                 {  
  17.                     temp = disOrderArray[j];  
  18.                     disOrderArray[j] = disOrderArray[j-1];  
  19.                     disOrderArray[j-1] = temp;  
  20.                 }  
  21.             }  
  22.         }  
  23.         return disOrderArray;  
  24.     }  
/**
     * Bubble sort
     * @param disOrderArray
     * @return
     */
    public static int[] BubbleSort(int[] disOrderArray) {
        int temp;
        // Layer 1 loop: Indicates the number of comparisons, such as length elements, and the number of comparisons is length-1.
        for(int i=0;i<disOrderArray.length-1;i++)
        {
            // Exchange the smallest number with the relative top of "bubbles". The smallest number comes up at one time, and the second smallest.
            for(int j=disOrderArray.length-1;j>i;j--)
            {
                // Here is < when it returns from small to large, and > when it returns from large to small.
                if(disOrderArray[j] < disOrderArray[j-1])
                {
                    temp = disOrderArray[j];
                    disOrderArray[j] = disOrderArray[j-1];
                    disOrderArray[j-1] = temp;
                }
            }
        }
        return disOrderArray;
    }

2. Quick Sorting

Idea: By one-time sorting, the waiting records are divided into two parts, one part of which has smaller keywords than the other part. Then the two parts can be sorted separately to achieve the purpose of ordering the whole sequence.

Time complexity: O(nlogn), at worst O(n^2)

Spatial complexity: O(1)

Stability: instability

  1. /* 
  2. * 
  3. * Quick sort 
  4. * 
  5. * Thoughts: 
  6. * By one-time sorting, the waiting records are divided into two separate parts, in which the keywords of one part of the records are smaller than those of the other. 
  7. * Then the two parts of records can be sorted separately to achieve the purpose of ordering the whole sequence. 
  8.  
  9. * The essence is to find a base (pivot, watershed, the role is that the left side is smaller than it, the right side is larger than it. Random, named base. 
  10. * Start at the right-most edge of the sequence to find something smaller than base 
  11. * ,If it's small, change the position so that base moves to the right (smaller than base in comparison) position (marked as temporary high bit), so that the right side of base is larger than base. 
  12. * Then, start at the leftmost edge of the sequence to find something larger than base 
  13. * ,If it's big, change the position so that the base moves to the left (larger than base in comparison) position (marked as temporary low bit), so that the left side of the base is smaller than base. 
  14.  
  15. * Cycle the above two steps until low = heigh, which makes it possible to really find the pivot, the watershed. Return to this location, the sequence on the left and right of the watershed, and recurse again, respectively. 
  16. */  
  17. public static int[] quickSort(int[] arr, int low, int heigh) {  
  18.     if(low < heigh)  
  19.     {  
  20.         int division = partition(arr, low, heigh);  
  21.           
  22.         quickSort(arr, low, division - 1);  
  23.           
  24.         quickSort(arr, division + 1, heigh);  
  25.     }  
  26.     return arr;  
  27. }  
  28.   
  29. //The watershed, the base, the left are smaller than this, and the right are larger.  
  30. private static int partition(int[] arr, int low, int heigh) {  
  31.     int base = arr[low]; //Make pivot (watershed) records with the first record of the subtable  
  32.     while (low < heigh)  
  33.     {    
  34.         //Change <= and >= in the following two while loops to get the order from large to small  
  35.         //Scanning alternately from both ends of the table to the middle, ranging from small to large  
  36.         while (low < heigh && arr[heigh] >= base)  
  37.         {  
  38.             heigh–;  
  39.         }  
  40.           
  41.         //If the high bit is less than base,base assigns to the current heigh bit, base moves to (swaps) here, and the right heigh bit is larger than base.  
  42.         swap(arr, heigh, low);  
  43.           
  44.         while(low < heigh && arr[low] <= base)  
  45.         {  
  46.             low++;  
  47.         }  
  48.           
  49.         //If there is a base in the lower position,  
  50.         swap(arr, heigh, low);  
  51.     }  
  52.       
  53.     //Now low=heigh  
  54.     return low;  
  55. }  
  56.   
  57. //Exchange size  
  58. private static void swap(int[] arr, int heigh, int low) {  
  59.     int temp = arr[heigh];  
  60.     arr[heigh] = arr[low];  
  61.     arr[low] = temp;  
  62. }  
   /*
    *
    * Quick sort
    *
    * thought: 
    * By one-time sorting, the waiting records are divided into two separate parts, in which the keywords of one part of the records are smaller than those of the other.
    * Then the two parts of records can be sorted separately to achieve the purpose of ordering the whole sequence.
    * 
    * The essence is to find a base (pivot, watershed, the role is that the left side is smaller than it, the right side is larger than it. Random, named base.
    * Start at the right-most edge of the sequence to find something smaller than base
    * If it's small, change the position so that the base moves to the right (smaller than base in comparison) position (marked as the temporary high bit), so that the right side of the base is larger than the base.
    * Then, start at the leftmost edge of the sequence to find something larger than base
    * If it is large, change the position, so that the base moves to the left (larger than base in comparison) position (marked as temporary low bit), so that the left side of the base is smaller than base
    * 
    * Cycle the above two steps until Low = heigh, which makes it possible to really find the pivot, the watershed. Return to this location, the sequence on the left and right of the watershed, and recurse again, respectively.
    */
    public static int[] quickSort(int[] arr, int low, int heigh) {
        if(low < heigh)
        {
            int division = partition(arr, low, heigh);

            quickSort(arr, low, division - 1);

            quickSort(arr, division + 1, heigh);
        }
        return arr;
    }

    // The watershed, the base, the left are smaller than this, and the right are larger.
    private static int partition(int[] arr, int low, int heigh) {
        int base = arr[low]; // Make pivotal (watershed) records with the first record of the subtable
        while (low < heigh)
        {  
            // Change <= and >= in the following two while loops to get the order from large to small
            // Scanning alternately from both ends of the table to the middle, ranging from small to large
            while (low < heigh && arr[heigh] >= base)
            {
                heigh--;
            }

            // If the high bit is less than base,base assigns the current heigh bit, base moves to (swaps) here, and the right side of the heigh bit is larger than base.
            swap(arr, heigh, low);

            while(low < heigh && arr[low] <= base)
            {
                low++;
            }

            // If the base is large at the lower level,
            swap(arr, heigh, low);
        }

        // Now low=heigh
        return low;
    }

    // swap size
    private static void swap(int[] arr, int heigh, int low) {
        int temp = arr[heigh];
        arr[heigh] = arr[low];
        arr[low] = temp;
    }

3. Direct selection ranking:

Thought: Each sorting will select the smallest (or largest) value, which will be placed after the sorted sequence.

Time complexity: O(n^2)

Spatial complexity: O(1)

Stability: instability

  1. /** 
  2.  * Direct Selection Sorting 
  3.  * Select the smallest value for each trip by direct selection sort 
  4.  * @param arr 
  5.  * @return 
  6.  */  
  7. public static int[] selectionSort(int[] arr) {  
  8.     for(int i=0;i<arr.length;i++)  
  9.     {  
  10.         for(int j=i+1;j<arr.length;j++)  
  11.         {  
  12.             if(arr[i] > arr[j])  
  13.             {  
  14.                 int temp = arr[j];  
  15.                 arr[j] = arr[i];  
  16.                 arr[i] = temp;  
  17.             }  
  18.         }  
  19.     }  
  20.     return arr;  
  21. }  
   /**
     * Direct Selection Sorting
     * Select the smallest value for each trip by direct selection sort
     * @param arr
     * @return
     */
    public static int[] selectionSort(int[] arr) {
        for(int i=0;i<arr.length;i++)
        {
            for(int j=i+1;j<arr.length;j++)
            {
                if(arr[i] > arr[j])
                {
                    int temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
        return arr;
    }

4. Heap Sorting

Thought: Heap sorting uses this heap data structure A sort designed algorithm Using the characteristics of arrays, you can quickly locate the elements of a specified index

Time complexity: O(nlogn)

Spatial complexity: O(1)

Stability: instability

  1. /** 
  2.  * Heap sort 
  3.  * Heapsort (Heapsort) is a sort algorithm designed by using heap as a data structure. It can quickly locate the elements of a specified index by using the characteristics of arrays. 
  4.  * @param arr 
  5.  * @return 
  6.  */  
  7. public static int[] heapSort(int[] arr) {  
  8.     int i;  
  9.     //Make arr a large top heap  
  10.     //From 0 to arr.length/2, these are nodes with children  
  11.     //It is meaningless to construct a large pile of nodes without children.  
  12.     for (i = arr.length / 2; i >= 0; i–)  
  13.     {  
  14.         heapAdjust(arr, i, arr.length - 1);  
  15.     }  
  16.     for (i = arr.length - 1; i > 0; i–)  
  17.     {  
  18.         swap(arr, 0, i);  
  19.         //Ar [0... i-1] Reconstructed into a large top heap  
  20.         heapAdjust(arr, 0, i - 1);  
  21.     }  
  22.     return arr;  
  23. }  
  24.   
  25. private static void heapAdjust(int[] arr, int s, int m) {  
  26.     int temp, j;  
  27.     temp = arr[s]; //Point to the root node of the temporary (relative to the root node)  
  28.     for (j = 2 * s; j <= m; j *= 2)   
  29.     {  
  30.         //If the right node is larger than the left node, the current node moves to the right node  
  31.         if (j < m && arr[j] < arr[j + 1])  
  32.         {  
  33.             //Point to the right node  
  34.             j++;  
  35.         }  
  36.         //The current parent node is larger than the node to which it is pointing  
  37.         //There is no need to do anything about it.  
  38.         if (temp >= arr[j])  
  39.         {  
  40.             break;  
  41.         }  
  42.           
  43.         //The current parent node is smaller than the next child node  
  44.         //Replace this child node with the parent node  
  45.         //The current location, if it is a leaf node, should be the smallest (relative to its ancestors)  
  46.         //The purpose of this method is to exchange the values of parent and child ren to construct a large root heap.  
  47.            
  48.         //Execution to this point indicates that the parent node of the current node (temporary root node is smaller than the current node)  
  49.         //Move the current node up and change position  
  50.         //It doesn't matter if arr[s] is overwritten, because temp records this value (the original root node (relative parent))  
  51.         arr[s] = arr[j];  
  52.            
  53.         //Now consider the current element as a temporary parent node  
  54.         //To find the child node of this element at this time, see if it is larger than the current value.  
  55.         //The last s points to the element currently traversed  
  56.         s = j;  
  57.     }  
  58.     arr[s] = temp;  
  59. }  
   /**
     * heap sort
     * Heapsort (Heapsort) is a sort algorithm designed by using heap as a data structure. It can quickly locate the elements of a specified index by using the characteristics of arrays.
     * @param arr
     * @return
     */
    public static int[] heapSort(int[] arr) {
        int i;
        // Make arr a large top heap
        // From 0 to arr.length/2, these are nodes with children
        // It's meaningless to construct a big pile of nodes without children.
        for (i = arr.length / 2; i >= 0; i--)
        {
            heapAdjust(arr, i, arr.length - 1);
        }
        for (i = arr.length - 1; i > 0; i--)
        {
            swap(arr, 0, i);
            // Reconstruct arr[0...i-1] into a large top heap
            heapAdjust(arr, 0, i - 1);
        }
        return arr;
    }

    private static void heapAdjust(int[] arr, int s, int m) {
        int temp, j;
        temp = arr[s]; // points to the root node of the temporary (relative to the root node)
        for (j = 2 * s; j <= m; j *= 2) 
        {
            // If the right node is larger than the left node, the current node moves to the right node
            if (j < m && arr[j] < arr[j + 1])
            {
                // Point to the right node
                j++;
            }
            // The current parent node is larger than the node to which it is pointing.
            // There is no need to do anything about it.
            if (temp >= arr[j])
            {
                break;
            }

            // The current parent node is smaller than the next child node
            // Replace this child node with the parent node
            // The current location, if it is a leaf node, should be the smallest (relative to its ancestors).
            // The purpose of this method is to exchange the values of parent and child ren to construct a large root heap.

            // Execution to this point indicates the parent of the current node (temporary root node is smaller than the current node).
            // Move the current node up and change position
            // It doesn't matter if arr[s] is overwritten, because temp records this value (the original root node (relative parent)).
            arr[s] = arr[j];

            // Now consider the current element as a temporary parent node
            // To find the child node of this element at this time, see if it is larger than the current value.
            // The last s points to the element currently traversed
            s = j;
        }
        arr[s] = temp;
    }



5. Insertion sort

Idea: Insert a record into an ordered table, and get a new ordered table with 1 record added. By default, the first element is treated as an ordered table, and then the next element is inserted in turn.

Time complexity: O(n^2)

Spatial complexity: O(1)

Stability: Stability

  1. /** 
  2.  * Insertion sort 
  3.  * Idea: Insert a record into an ordered table, and get a new ordered table with the number of records increasing by 1. 
  4.  * By default, consider the first element as an ordered table, inserting the desired element at a time 
  5.  * Time complexity O(n^2) 
  6.  * Spatial complexity O(1) is suitable for small number of records 
  7.  * @param arr 
  8.  * @return 
  9.  */  
  10. public static int[] InsertSort(int[] arr) {  
  11.     //Arrangement from small to large  
  12.     for(int i=1;i<arr.length;i++)  
  13.     {  
  14.         //Elements to be inserted  
  15.         int temp = arr[i];  
  16.         int j;  
  17.         for(j=i-1;j>=0 && temp < arr[j];j–)  
  18.         {  
  19.             //When the insertion element is smaller than the existing one, move the existing one back until the element is larger than the insertion element or has reached the top of the sequence.  
  20.             arr[j+1] = arr[j];  
  21.         }  
  22.         arr[j+1] = temp;  
  23.     }  
  24.     return arr;  
  25. }  
   /**
     * Insertion sort
     * Idea: Insert a record into an ordered table, and get a new ordered table with the number of records increasing by 1.
     * By default, consider the first element as an ordered table, inserting the desired element at a time
     * Time complexity O(n^2)
     * Spatial complexity O(1) is suitable for small number of records
     * @param arr
     * @return
     */
    public static int[] InsertSort(int[] arr) {
        // Arrangement from small to large
        for(int i=1;i<arr.length;i++)
        {
            // Elements to be inserted
            int temp = arr[i];
            int j;
            for(j=i-1;j>=0 && temp < arr[j];j--)
            {
                // When the insertion element is smaller than the existing one, move the existing one back until the element is larger than the insertion element or has reached the top of the sequence.
                arr[j+1] = arr[j];
            }
            arr[j+1] = temp;
        }
        return arr;
    }

6. Half-folded insertion sort

Idea: Half-insert sorting is rewritten based on direct insert sorting, which can reduce the number of "moves" and "comparisons"

Time complexity: O(n^2)

Spatial complexity: O(1)

Stability: Stability

  1. /** 
  2.  * Binary Insertion Sort 
  3.  * Advantages: Reduce the number of "comparisons" and "moves" 
  4.  * @param arr 
  5.  * @return 
  6.  */  
  7. public static int[] BInsertSort(int[] arr){  
  8.     for(int i=1;i<arr.length;i++)  
  9.     {  
  10.         //Elements to be inserted  
  11.         int temp = arr[i];  
  12.         int j;  
  13.         int low = 0, high = i-1;  
  14.         while(low <= high)  //Find the location of orderly insertion by halving in arr[low..high]  
  15.         {  
  16.             int m = (low + high)/2;//Halve  
  17.             if(temp < arr[m])  
  18.             {  
  19.                 high = m-1;  //Insertion point in lower half  
  20.             }  
  21.             else  
  22.             {  
  23.                 low = m+1;  //Insertion point in high half area  
  24.             }  
  25.         }  
  26.           
  27.         //Record shift  
  28.         for(j=i-1;j>=high+1;j–)  
  29.         {  
  30.             arr[j+1] = arr[j];  
  31.         }  
  32.         arr[j+1] = temp;  
  33.     }  
  34.     return arr;  
  35. }  
  /**
     * Half Insert Sort
     * Advantages: Reduce the number of "comparisons" and "moves"
     * @param arr
     * @return
     */
    public static int[] BInsertSort(int[] arr){
        for(int i=1;i<arr.length;i++)
        {
            // Elements to be inserted
            int temp = arr[i];
            int j;
            int low = 0, high = i-1;
            While (low <= high) // Halve in arr[low..high] to find the location of the ordered insertion
            {
                Int m = Low + high) / 2; // half
                if(temp < arr[m])
                {
                    high = m-1; // insertion point in the lower half
                }
                else
                {
                    low = m+1; // insertion point in high half
                }
            }

            // Record postponement
            for(j=i-1;j>=high+1;j--)
            {
                arr[j+1] = arr[j];
            }
            arr[j+1] = temp;
        }
        return arr;
    }

Seventh, Hill Ranking:

Thought: Hill sort is also a sort of insertion sort, which is directly improved for insertion sort. This method is also called "reduced incremental sort".

Time complexity: O(n^2)

Spatial complexity: O(1)

Stability: instability

  1. /** 
  2.  * Hill Sorting (Reduced Incremental Sorting) 
  3.  * Hill sort is also a sort of insertion sort, except that it has an increment, and the last increment must be 1. 
  4.  * @param arr 
  5.  * @return 
  6.  */  
  7. public static int[] ShellInsert(int[] arr){  
  8.     int step = arr.length/2//Increment  
  9.     //Guarantee the last increment of 1  
  10.     while(step >= 1)  
  11.     {  
  12.         for(int i=step;i<arr.length;i++)  
  13.         {  
  14.             int temp = arr[i];  
  15.             int j = 0;  
  16.               
  17.             //The difference between root insertion sort is here  
  18.             for(j=i-step;j>=0 && temp<arr[j];j-=step)  
  19.             {  
  20.                 arr[j+step] = arr[j];  
  21.             }  
  22.             arr[j+step] = temp;  
  23.         }  
  24.         step /= 2;  
  25.     }  
  26.     return arr;  
  27. }  
  /**
     * Hill Sorting (Reduced Incremental Sorting)
     * Hill sort is also a sort of insertion sort, except that it has an increment, and the last increment must be 1.
     * @param arr
     * @return
     */
    public static int[] ShellInsert(int[] arr){
        int step = arr.length/2; // take increments
        // Guarantee the last increment of 1
        while(step >= 1)
        {
            for(int i=step;i<arr.length;i++)
            {
                int temp = arr[i];
                int j = 0;

                // The difference between root insertion sort is here
                for(j=i-step;j>=0 && temp<arr[j];j-=step)
                {
                    arr[j+step] = arr[j];
                }
                arr[j+step] = temp;
            }
            step /= 2;
        }
        return arr;
    }

8. Merging and Sorting

Idea: Merging and sorting is to combine two or more ordered tables into an ordered table. The algorithm is implemented by dividing and conquering.

Time complexity: O(nlogn)

Spatial complexity: O(n)

Stability: Stability

  1. /** 
  2.  * Merge sort 
  3.  * Merging and sorting is to combine two or more ordered tables into a new ordered table. 
  4.  * Time complexity O(nlog2n) 
  5.  * @param arr 
  6.  * @param tempArray 
  7.  * @param left 
  8.  * @param right 
  9.  * @return 
  10.  */  
  11. public static int[] mergeSort(int[] arr, int left,int right) {  
  12.     if (left < right)  
  13.     {  
  14.         //Segmentation location  
  15.         int middle = (left + right) / 2;  
  16.         //Recursively partitioning the left sequence of arrays  
  17.         mergeSort(arr, left, middle);  
  18.         //Recursively partitioning the right sequence of arrays  
  19.         mergeSort(arr, middle+1, right);  
  20.         //Merge left and right arrays  
  21.         Merge(arr, left, middle, right);  
  22.     }  
  23.     return arr;  
  24. }  
  25.   
  26. private static void Merge(int[] arr, int left, int middle,int right) {  
  27.     int[] tempArray = new int[arr.length];    
  28.     int leftEnd = middle;  
  29.     int rightStart = middle+1;  
  30.     //Subscription of temporary arrays  
  31.     int tempIndex = left;  
  32.     int tmp = left;  
  33.       
  34.     //The case where neither interval of the first cycle ends  
  35.     while ((left <= leftEnd) && (rightStart <= right))  
  36.     {  
  37.         //The left is smaller than the right, insert the left first.  
  38.         if (arr[left] < arr[rightStart])  
  39.         {  
  40.             tempArray[tempIndex++] = arr[left++];  
  41.         }  
  42.         else  
  43.         {  
  44.             tempArray[tempIndex++] = arr[rightStart++];  
  45.         }  
  46.     }  
  47.       
  48.     //Judging whether the left sequence ends  
  49.     while (left <= leftEnd)  
  50.     {  
  51.         tempArray[tempIndex++] = arr[left++];  
  52.     }  
  53.       
  54.     //Judging whether the right sequence ends  
  55.     while (rightStart <= right)  
  56.     {  
  57.         tempArray[tempIndex++] = arr[rightStart++];  
  58.     }  
  59.       
  60.     //Copy the contents of the temporary array back to the original array.  
  61.        //(The contents of the original left-right range are copied back to the original array)  
  62.     while (tmp <= right) {    
  63.            arr[tmp] = tempArray[tmp++];    
  64.        }   
  65. }  
    /**
     * Merge Sort
     * Merging and sorting is to combine two or more ordered tables into a new ordered table.
     * Time complexity O(nlog2n)
     * @param arr
     * @param tempArray
     * @param left
     * @param right
     * @return
     */
    public static int[] mergeSort(int[] arr, int left,int right) {
        if (left < right)
        {
            // Segmentation location
            int middle = (left + right) / 2;
            // Recursively partitioning the left sequence of arrays
            mergeSort(arr, left, middle);
            // Recursively partitioning the right sequence of arrays
            mergeSort(arr, middle+1, right);
            // Merge left and right arrays
            Merge(arr, left, middle, right);
        }
        return arr;
    }

    private static void Merge(int[] arr, int left, int middle,int right) {
        int[] tempArray = new int[arr.length];  
        int leftEnd = middle;
        int rightStart = middle+1;
        // Subscription of Temporary Array
        int tempIndex = left;
        int tmp = left;

        // The case where neither interval of the first cycle ends
        while ((left <= leftEnd) && (rightStart <= right))
        {
            // The left side is smaller than the right side. Insert the left side first.
            if (arr[left] < arr[rightStart])
            {
                tempArray[tempIndex++] = arr[left++];
            }
            else
            {
                tempArray[tempIndex++] = arr[rightStart++];
            }
        }

        // Judging whether the left sequence ends
        while (left <= leftEnd)
        {
            tempArray[tempIndex++] = arr[left++];
        }

        // Judging whether the right sequence ends
        while (rightStart <= right)
        {
            tempArray[tempIndex++] = arr[rightStart++];
        }

        // Copy the contents of the temporary array back to the original array  
        // (The contents of the original left-right range are copied back to the original array)
        while (tmp <= right) {  
            arr[tmp] = tempArray[tmp++];  
        } 
    }

9. cardinal ordination

Thought: The cardinality is sorted first according to the low position, then collected; then sorted by the high position, then collected, and so on, until the highest position.

Note: It means that keywords are classified into Radix boxes. When keywords are numbers, the base number is 10. When keywords are letters, the base number is 26.

Time complexity: O(n+d)

Spatial complexity: O(n)

Stability: Stability

  1. /** 
  2.  * Radix sorting 
  3.  * @radix The cardinality means that Radix boxes are categorized according to keywords. When keywords are numbers, the cardinality is 10. 
  4.  * @d Number of ranking elements 
  5.  * @return 
  6.  */  
  7. public static int[] RadixSort(int[] arr, int radix, int d){  
  8.     //For temporary elements  
  9.     int[] temp = new int[arr.length];  
  10.     //For counting sort  
  11.     int[] count = new int[radix];  
  12.     int divide = 1;  
  13.       
  14.     for(int i=0;i<d;i++)  
  15.     {  
  16.         System.arraycopy(arr, 0, temp, 0, arr.length);  
  17.           
  18.         //Reset the count array to start counting the next keyword.  
  19.         Arrays.fill(count, 0);  
  20.           
  21.         //Calculate subkeywords for each data to be sorted  
  22.         for(int j=0;j<arr.length;j++)  
  23.         {  
  24.             int tempKey = (temp[j]/divide)%radix;  
  25.             count[tempKey]++;  
  26.         }  
  27.           
  28.         for(int j=1;j<radix;j++)  
  29.         {  
  30.             count[j] = count[j] + count[j-1];  
  31.         }  
  32.           
  33.         //Sort the specified data by subkeywords  
  34.         for(int j=arr.length-1;j>=0;j–)  
  35.         {  
  36.             int tempKey = (temp[j]/divide)%radix;  
  37.             count[tempKey]–;  
  38.             arr[count[tempKey]] = temp[j];  
  39.         }  
  40.           
  41.         divide = divide * radix;  
  42.     }  
  43.     return arr;  
  44. }  
    /**
     * cardinal sorting
     *@ radix cardinality means radix boxes categorized by keywords. When keywords are numbers, the cardinality is 10
     *@ The number of digits of d-sorted elements  
     * @return
     */
    public static int[] RadixSort(int[] arr, int radix, int d){
        // For temporary elements
        int[] temp = new int[arr.length];
        // For counting sort
        int[] count = new int[radix];
        int divide = 1;

        for(int i=0;i<d;i++)
        {
            System.arraycopy(arr, 0, temp, 0, arr.length);

            // Reset the count array to start counting the next keyword  
            Arrays.fill(count, 0);

            // Calculate subkeywords for each data to be sorted  
            for(int j=0;j<arr.length;j++)
            {
                int tempKey = (temp[j]/divide)%radix;
                count[tempKey]++;
            }

            for(int j=1;j<radix;j++)
            {
                count[j] = count[j] + count[j-1];
            }

            // Sort specified data by subkeywords  
            for(int j=arr.length-1;j>=0;j--)
            {
                int tempKey = (temp[j]/divide)%radix;
                count[tempKey]--;
                arr[count[tempKey]] = temp[j];
            }

            divide = divide * radix;
        }
        return arr;
    }


  1. public static void main(String[] args) {  
  2.         //By default, the base is arranged from small to large  
  3. //      int[] disOrderArray = {3,1,5,7,0};  
  4.         //Bubble sort  
  5. //      disOrderArray = BubbleSort(disOrderArray);  
  6.           
  7.         //Quick sort  
  8. //      disOrderArray = quickSort(disOrderArray, 0, disOrderArray.length-1);  
  9.           
  10.         //Direct Selection Sorting  
  11. //      disOrderArray = selectionSort(disOrderArray);  
  12.           
  13.         //Heap sort  
  14. //      disOrderArray = heapSort(disOrderArray);  
  15.           
  16.         //Direct insertion sort  
  17. //      disOrderArray = InsertSort(disOrderArray);  
  18.           
  19.         //Half Insert Sort (Binary Search Sort)  
  20. //      disOrderArray = BInsertSort(disOrderArray);  
  21.           
  22.         //Shell Sort  
  23. //      disOrderArray = ShellInsert(disOrderArray);  
  24.           
  25.         //Merge sort  
  26. //      disOrderArray = mergeSort(disOrderArray, 0, disOrderArray.length-1);  
  27.           
  28.         //Radix sorting  
  29.         int[] disOrderArray = {3,2,3,2,5,333,45566,2345678,78,990,12,432,56};  
  30.           
  31.         disOrderArray = RadixSort(disOrderArray, 107);  
  32.         for(int i=0;i<disOrderArray.length;i++)  
  33.         {  
  34.             System.out.print(disOrderArray[i]+" ");  
  35.         }  
  36.     }  
public static void main(String[] args) {
        // By default, the base is arranged from small to large
//      int[] disOrderArray = {3,1,5,7,0};
        // Bubble sort
//      disOrderArray = BubbleSort(disOrderArray);

        // Quick sort
//      disOrderArray = quickSort(disOrderArray, 0, disOrderArray.length-1);

        // Direct Selection Sorting
//      disOrderArray = selectionSort(disOrderArray);

        / / heap sort
//      disOrderArray = heapSort(disOrderArray);

        // Direct insertion sort
//      disOrderArray = InsertSort(disOrderArray);

        // Half Insert Sort (Binary Search Sort)
//      disOrderArray = BInsertSort(disOrderArray);

        // Hill sort
//      disOrderArray = ShellInsert(disOrderArray);

        // Merge Sort
//      disOrderArray = mergeSort(disOrderArray, 0, disOrderArray.length-1);

        // cardinal sorting
        int[] disOrderArray = {3,2,3,2,5,333,45566,2345678,78,990,12,432,56};

        disOrderArray = RadixSort(disOrderArray, 10, 7);
        for(int i=0;i<disOrderArray.length;i++)
        {
            System.out.print(disOrderArray[i]+" ");
        }
    }

The basic sorting algorithms for data structures are almost complete.


Add a binary search algorithm: similar to the half-fold search algorithm

Time complexity: O(logn)

  1. /** 
  2.  * Two points search 
  3.  * @param arr 
  4.  * @param searchnum Elements to be looked up 
  5.  * @return 
  6.  */  
  7. public static int BSearch(int[] arr, int searchnum){  
  8.     int low = 0;  
  9.     int high = arr.length-1;  
  10.     while(low<=high)  
  11.     {  
  12.         int m = (low+high)/2;  
  13.         if(searchnum == arr[m])  
  14.         {  
  15.             return m;  
  16.         }  
  17.         else if(searchnum < arr[m])  
  18.         {  
  19.             high = m-1;  
  20.         }  
  21.         else  
  22.         {  
  23.             low = m+1;  
  24.         }  
  25.     }  
  26.     return -1;  
  27. }  
   /**
     * Binary search
     * @param arr
     *@ Param search num element to be found
     * @return
     */
    public static int BSearch(int[] arr, int searchnum){
        int low = 0;
        int high = arr.length-1;
        while(low<=high)
        {
            int m = (low+high)/2;
            if(searchnum == arr[m])
            {
                return m;
            }
            else if(searchnum < arr[m])
            {
                high = m-1;
            }
            else
            {
                low = m+1;
            }
        }
        return -1;
    }



This paper refers to: http://blog.csdn.net/tan313/article/details/51146170

Posted by borris_uk on Thu, 30 May 2019 12:51:07 -0700