The examples in this article share with you the specific code of C# implementation merge sorting for your reference. The specific content is as follows
Code:
//Group sort (target array, start position of subtable, end position of subtable) private static void MergeSortFunction(int[] array, int first, int last) { try { if (first < last) //The length of the subtable is greater than 1, then the following recursive processing will be entered. { int mid = (first + last) / 2; //The location of sub-table division MergeSortFunction(array, first, mid); //Recursively divide the divided left subtable MergeSortFunction(array, mid + 1, last); //Recursively divide the divided right subtable MergeSortCore(array, first, mid, last); // Orderly integrate left and right sub-tables (the core part of merge sorting) } } catch (Exception ex) { } } //The core part of merge sorting: merge two ordered left and right subtables (differentiated by mid) into an ordered table private static void MergeSortCore(int[] array, int first, int mid, int last) { try { int indexA = first; //The starting position of the sub-table on the left int indexB = mid + 1; //The starting position of the sub-table on the right int[] temp = new int[last + 1]; //Declare an array (stagely store all ordered sequences of left and right subtables): the length is equal to the sum of the lengths of left and right subtables. int tempIndex = 0; while (indexA <= mid && indexB <= last) //Do traverse left and right sub-tables. If one of the sub-tables has been traversed, the loop will jump out { if (array[indexA] <= array[indexB]) //The number of the left subtable at this time <= the number of the right subtable at this time { temp[tempIndex++] = array[indexA++]; //Put the number of the left subtable into the temporary array and traverse the subtable of the left subtable++ } else//Number of the left subtable at this time >Number of the right subtable at this time { temp[tempIndex++] = array[indexB++]; //Put the number of the right subtable into the temporary array and traverse the subtable of the right subtable++ } } //After one side sub-table is traversed, the loop jumps out and the remaining numbers on the other side sub-table are placed in the temporary array at one time (ordered) while (indexA <= mid) { temp[tempIndex++] = array[indexA++]; } while (indexB <= last) { temp[tempIndex++] = array[indexB++]; } //Write the ordered sequence in the temporary array to the target array setting position to make the merged array segments orderly tempIndex = 0; for (int i = first; i <= last; i++) { array[i] = temp[tempIndex++]; } } catch (Exception ex) { } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.