Sorting methods

Sorting methods

Sorting methods are ways to sort arrays in either ascending or descending order.WE sort arrays so they are easier to use. You  also use sorting methods to match two data sets, or presenting something in a orderly way.When sorting array we often use equals compareTo and/or compare methods. Also O( . . .) stands for time it takes for the program to sort in the worst case.

Merge-In merge sort you first make sure that there is more than one element if there is only one don’t do anything, if there are two swap them if you need to , if there are more than two split the array into to approximately equal halves, sort the first half of the array and the second half, and then merge the two halves back into one sorted array. Recursion is often used with this sorting method since it has a base case (when there is only one or two elements). It’s a O(n^2)

Quick-in quick sort you pick one element to be the pivot and then you sort around that pivot so that to the left are smaller elements and to the right are bigger elements. THen apply recursion to the right and left halves of the array.  It’s a O(n log n) algorithm.

Selection- In a selection sort you initialize a variable to the size of the array, find the largest element among the n elements, subtract one from n and repeat those steps except for initialization until n is less than or equal to 2.It’s a O(n^2) algorithm.

Insertion-In insertion sort you make n equal  to 1. Save the next element and find the place to insert it among the first n, shift elements as necessary and insert the saved one in the vacant slot, increment n by 1 and repeat steps except initialization until n is greater than array length. It’s a O(n^2) algorithm.