Question
Bubble Sort Iterate over the list, compare each element with the next element, and if the next element is smaller swap the two. For each
Bubble Sort
- Iterate over the list, compare each element with the next element, and if the next element is smaller swap the two.
- For each swap completed increment a counter.
- If at the end of the list the swap counter is greater than 0, reset it to zero and start again at step 1.
- If the swap counter == 0, then the array is in sorted order.
Array to be sorted: [7 4 6 5 3] Pass 1: [4 6 5 3 7] Pass 2: [4 5 3 6 7] Pass 3: [4 3 5 6 7] Pass 4: [3 4 5 6 7]
Insertion Sort
The Insertion Sort algorithm is the method that many people use to sort playing cards. Pick up one card at a time and insert it so that the cards stay sorted.
Array to be sorted: [7 4 6 5 3] Pass 1: [4 7 6 5 3] Pass 2: [4 6 7 5 3] Pass 3: [4 5 6 7 3] Pass 4: [3 4 5 6 7]
Merge Sort
Merge sort is a more efficient sorting algorithm than Selection Sort, Bubble Sort and Insertion Sort, with a time complexity of O(n log n). It has a relatively high space complexity of O(n) compared to some other algorithms that we won't cover in this class. The Java libraries implement MergeSort, but only in specific cases.
mergeSort(arrayToSort[], leftIndex, rightIndex)
If rightIndex > leftIndex:
- Find the middle point to divide the array into two halves: int middleIndex = (leftIndex + rightIndex) / 2
- Call mergeSort for first half: mergeSort(arrayToSort, leftIndex, middleIndex)
- Call mergeSort for second half: mergeSort(arrayToSort, middleIndex + 1, rightIndex)
- Merge the two halves sorted in step 2 and 3: merge(arrayToSort, leftIndex, middleIndex, rightIndex)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started