Android programmers often encounter algorithmic problems, seven commonly used algorithms

Keywords: Android REST

Common Algorithms for Android
1. Insertion sort algorithm

The basic idea of insertion sorting is that in the process of traversing the array, assuming that the elements before the ordinal number i, i.e. [0.i-1], have been sorted out, we need to find the correct position K of the element x corresponding to i, and in the process of searching for the position k, we move the elements that have been compared backwards one by one to "vacate the position" for the element x, and finally assign the value of the element corresponding to K to x, one. Generally, the time complexity and space complexity of insertion sort are O(n2) and O(1), respectively.

/**
* @param int[] Unordered array
* @return int[] Ranked array
 */
 
 public int[] sortInsert(int[] array){
      for(int i=1;i<array.length;i++){
           int temp = array[i];
           int j;
           for(j=i-1;j >= 0 && temp< array[j]; j--){
                array[j + 1] = array[j];
           }
           array[j + 1] = temp;
      }
      return array;
 }

2. Selective Sorting Algorithms

The basic idea of sorting selection is to traverse the array. Representing the current sorting sequence number with i, you need to use the remaining [i... The minimum value is found i n n-1, and then the minimum value is exchanged with the value pointed to by I. Because there is a sub-process of choosing the maximum value in the process of determining the elements, people call it choosing order vividly. The time complexity and space complexity of selection sort are O(n2) and O(1), respectively.

/**
 * @param int[] Unordered array
 * @return int[] Ranked array
 */
 
 public int[] sortSelect(int[] arr){
      for (int i = 0; i < arr.length; i++) {
            int miniPost = i;
            for (int m = i + 1; m < arr.length; m++) {
                  if (arr[m] < arr[miniPost]) {
                        miniPost = m;
                  }
            }
 
            if (arr[i] > arr[miniPost]) {
                  int temp;
                  temp = arr[i];
                  arr[i] = arr[miniPost];
                  arr[miniPost] = temp;
           }
      }
      return arr;
 }

3. Bubble Sorting Algorithms

Bubble sorting is to sink larger numbers at the bottom and float smaller ones at the top.

/**
* @param int[] Unordered array
* @return int[] Ranked array
 */
 
public int[] sortBubble(int[] array){
     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<array.length-1;i++){
          for (int j = array.length - 1; j > i; j--) {
                if (array[j] < array[j - 1]) {
                     temp = array[j];
                     array[j] = array[j - 1];
                     array[j - 1] = temp;
                }
          }
     }
     return array;
}

4. Quick Sorting Algorithms

By one-time sorting, the records to be arranged are divided into two separate parts. Some of the keywords recorded are smaller than the keywords of the other part. Then the two parts of the 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 of the left side is smaller than it, the right side is larger than it. Random, named base, head. Start from the rightmost side of the sequence to find smaller than base, if smaller, change the position, so that base moves to the right side (smaller than base in comparison) just now (marked as temporary high bit), so that the right side of base is larger than base. Then, start looking for bigger than base from the leftmost side of the sequence, if it is bigger, change the position, so base moves to the left side (larger than base in comparison) just now (designated as temporary low bit), so that the left side of base is smaller than base, and cycle the above two steps until Low = heigh, which makes it possible to really find the pivot, the watershed. Return to this position, the sequence on the left and right side of the watershed, and recurse again, respectively. .

/**
 * @param int[] Unordered array
 * @return int[] Ranked array
 */
 
public int[] sortQuick(int[] array){
     return quickSort(array, 0, array.length-1);
}
 
private 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 int partition(int[] arr, int low, int heigh) {
      int base = arr[low]; //Make pivot (watershed) records with the first record of the subtable
      while (low < heigh) { //Scanning alternately from both ends of the table to the middle
            while (low < heigh && arr[heigh] >= base) {
                 heigh--;
            }
            // Base assigns the current heigh bit. Base moves to (swaps) here. The right side of the heigh bit is larger than base.
            swap(arr, heigh, low);
            while (low < heigh && arr[low] <= base) {
                  low++;
            }
            // If the left side is larger than the base value, change the position.
            swap(arr, heigh, low);
      }
      // now low = heigh;
      return low;
}
 
private void swap(int[] arr, int a, int b) {
      int temp;
      temp = arr[a];
      arr[a] = arr[b];
      arr[b] = temp;
}

5. Merge Sorting Algorithms

Merge sort is realized by recursion, which belongs to "divide and conquer", dividing the target array into two parts, then sorting the two arrays separately. After sorting, the two arrays sorted are "merged" together. The most important process of merge sort is the merge process. In the merge process, additional two numbers that need to be merged are needed. Space with the same group length

/**
 * @param int[] Unordered array
 * @return int[] Ranked array
 */
private int[] sort(int[] nums, int low, int high) {
      int mid = (low + high) / 2;
      if (low < high) {
          // left
          sort(nums, low, mid);
          // Right
          sort(nums, mid + 1, high);
          // Merge left and right
          merge(nums, low, mid, high);
     }
     return nums;
}
private void merge(int[] nums, int low, int mid, int high) {
      int[] temp = new int[high - low + 1];
      int i = low;// Left pointer
      int j = mid + 1;// Right pointer
      int k = 0;
      // Move smaller numbers to new arrays first
      while (i <= mid && j <= high) {
          if (nums[i] < nums[j]) {
               temp[k++] = nums[i++];
          } else {
               temp[k++] = nums[j++];
          }
      }
      // Move the remaining number on the left into the array
      while (i <= mid) {
           temp[k++] = nums[i++];
      }
      // Move the remaining number on the right into the array
      while (j <= high) {
           temp[k++] = nums[j++];
      }
      // Override nums arrays with new arrays
      for (int k2 = 0; k2 < temp.length; k2++) {
           nums[k2 + low] = temp[k2];
      }
 }
 
public int[] sortMerge(int[] array) {
     return sort(array, 0, array.length - 1);
}

6. Hill sorting algorithm

Hill sort was born because insertion sort encounters the problem of moving too many elements when dealing with large arrays. The idea of Hill sort is to divide a large array into several small arrays and divide it into gaps, such as array [1, 2, 3, 4, 5, 6, 7, 8]. If it is divided by gap = 2, it can be divided into [1, 3, 5, 7] and [2, 4, 6, 8] (corresponding, such as gap = 3, then the array is divided into [1, 4, 7], [2, 5, 8], [3, 6]) and then divided into [1, 4, 7], [2, 5, 8], [3, 6]. Do not insert and sort the partitioned arrays, and then reduce the gap value after each sub-array has been sorted, repeat the previous steps until gap = 1, that is, insert and sort the whole array. At this time, the array is basically fast sorted, so the elements that need to move will be very small, solving the problem of insert and sort moving more times when dealing with large-scale arrays. The problem.

Hill sort is an improved version of insertion sort. It is helpful to improve efficiency when the data volume is large. It is better to use Insertion Sort directly when the data volume is small.

/**
* @param int[] Unordered array
* @return int[] Ranked array
 */
 
public int[] sortShell(int[] array) {
     // Increment
     int step = array.length / 2;
     while (step >= 1) {
          for (int i = step; i < array.length; i++) {
               int temp = array[i];
               int j = 0;
               // Here's the difference from insertion sort
               for (j = i - step; j >= 0 && temp < array[j]; j -= step) {
                     array[j + step] = array[j];
               }
               array[j + step] = temp;
          }
          step /= 2;
     }
     return array;
}

7. Heap Sorting Algorithms

The essence is to construct a large top heap first. parent is bigger than child. Root node is the largest node that interchanges the position of the largest node (root) with the tail node (last node, smaller) and the last tail node, which is now the largest, the rest, from the beginning of the first element to the front of the tail node, constructs a large top heap recursion.

/**
 * @param int[] Unordered array
 * @return int[] Ranked array
 */
public int[] sortHeap(int[] array) {
     buildHeap(array);// Build heap
     int n = array.length;
     int i = 0;
     for (i = n - 1; i >= 1; i--) {
          swap(array, 0, i);
          heapify(array, 0, i);
     }
 
     return array;
}
 
private void buildHeap(int[] array) {
     int n = array.length;// Number of elements in an array
     for (int i = n / 2 - 1; i >= 0; i--)
          heapify(array, i, n);
}
 
private void heapify(int[] A, int idx, int max) {
      int left = 2 * idx + 1;// Left child's subscript (if it exists)
      int right = 2 * idx + 2;// Left child's subscript (if it exists)
      int largest = 0;// Find the subscript of the maximum node in three nodes
      if (left < max && A[left] > A[idx])
            largest = left;
      else
            largest = idx;
      if (right < max && A[right] > A[largest])
            largest = right;
            if (largest != idx) {
                  swap(A, largest, idx);
                  heapify(A, largest, max);
            }
      }
}
// The heap building function considers that only s is in [s, m].
// The corresponding keywords do not satisfy the definition of large-top heap, so that [s, m] becomes large-top heap by adjusting.=====================================================
public static void heapAdjust(int[] array, int s, int m) {
      // Use 0 subscript element as temporary storage unit
      array[0] = array[s];
      // Screening down the larger nodes of the child
      for (int j = 2 * s; j <= m; j *= 2) {
            // Guarantee that j is the subscript of older children's node, J < m guarantees that j + 1 <= m does not cross the boundary
            if (j < m && array[j] < array[j + 1]) {
                   j++;
            }
            if (!(array[0] < array[j])) {
                   break;
            }
            // If the S position is small, the older children should be moved up.
            array[s] = array[j];
            // The older child's value becomes the smaller value of S-bit, which may cause the imbalance of the top heap, so it is necessary to screen the heap where it is located.
            s = j;
      }
      // If the S bit is large, the value will remain unchanged; otherwise, the S bit will move downward to 2*s, 4*s,....
      array[s] = array[0];
}```

Posted by BAM1979 on Wed, 15 May 2019 07:25:09 -0700