1. Bubble Sort
Two numbers are compared in size, and they are exchanged in pairs, like bubbles in water, the larger number sinks and the smaller number pops up.
Algorithm description :
1. Compare adjacent elements. If the first is greater than the second, swap them both;
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end, so that the last element should be the largest number;
3. Repeat the above steps for all elements, except the last one;
4. Repeat steps 1~3 until the sorting is complete.
Animation demo diagram:
oc code :
- (NSArray*)bubbleSort:(NSArray*)temArr{
NSMutableArray *arr = [NSMutableArray arrayWithArray: temArr];
NSInteger count = arr.count;
for (int i = 0; i < count; i++) { // number of loops
for (int j = 0; j < count - 1 - i; j++) { // comparison times
if ([arr[j] intValue] > [arr[j+1] intValue]) {
NSNumber *temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
Swift Code:
func bubbleSort(temArr: [Int] ) -> [Int] {
if temArr.count == 0 {
return []
}
var arr = temArray
let count = arr.count
for i in 0..<count { // number of loops
for j in 0..<count - 1 - i { // number of comparisons
if (arr[j] > arr[j + 1] ) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr
}
2. Quick Sort
1. Pick an element from the sequence as a benchmark.
2. Rearrange the number sequence, put all the ones smaller than the benchmark in front of the benchmark, and vice versa (the same size can be on either side). After completion, the benchmark is in the middle of the partition.
3. Sort the subsequences smaller than the reference element and the heavy rain reference element through recursive calls
Algorithm process diagram:
oc code :
// data array
NSArray *temArr = @[@30,@40, @60, @10, @20, @50];
NSMutableArray *arr = [NSMutableArray arrayWithArray:temArr];
[self quickSort:arr low:0 hight: arr.count - 1];
NSLog(@"%@",arr);
- (void)quickSort:(NSMutableArray*)temArr low: (NSInteger)low hight: (NSInteger)hight{
if (low >= hight) {
return;
}
NSInteger i = low;
NSInteger j = hight;
id key = temArr[i]; // reference base
while (i < j) {
while (i < j && [temArr[j] intValue] >= [key intValue]) { // j digits on the right are greater than the base number and the position remains unchanged
j--;
}
if (i == j) { // The positions of i and j coincide to end this cycle. When the key is the smallest number at present, the situation of i=j will appear.
break;
}
temArr[i] = temArr[j]; //The j digit on the right is less than the base position and the i digit exchange
while (i < j && [temArr[i] intValue] <= [key intValue]) {
i++;
}
if (i == j) { // When the key is the largest number (before m[j]), i=j will appear
break;
}
temArr[j] = temArr[i];
}
temArr[i] = key; // When i and j coincide, the current cycle ends, and the key is placed in the position of i (the number on the left is smaller than the key, and the number on the right is larger than the key)
// The left and right sides of the key are respectively quickly sorted
[self quickSort:temArr low:low hight:i - 1]; // left recursion
[self quickSort:temArr low:i + 1 hight:hight]; // right recursion
}
Swift code :
var array = [30,40,60,10,20,50]
quickSort(arr: &array, low: 0, hight: array.count - 1 )
print(array)
func quickSort(arr: inout [Int], low: Int, hight: Int ) {
if low >= hight { // recursive end condition
return
}
var i = low;
var j = hight;
let key = arr[i] // base
while i < j {
// Start comparison from the right, the position of the number larger than the key remains unchanged
while i < j && arr[j] >= key {
j -= 1
}
// As long as there is a number smaller than key, put this number into the position of i on the left
arr[i] = arr[j]
// Start comparison from the left, the position of the number smaller than the key remains unchanged
while i < j && arr[i] <= key {
i += 1
}
// As long as there is a number larger than the key, put this number into the j position on the right
arr[j] = arr[i]
}
arr[i] = key // When i and j coincide, the current cycle ends, and the key is placed in the position of i (the numbers on the left are smaller than the key, and the numbers on the right are larger than the key)
// The left and right sides of the key are respectively quickly sorted
quickSort(arr: &arr, low: low, hight: i - 1) // left recursive
quickSort(arr: &arr, low: i + 1, hight: hight) // right recursion
}
3. Insertion Sort
1. Starting from the first element, the element can be considered to have been sorted;
2. Take out the next element and scan from back to front in the sorted element sequence;
3. If the element (sorted) is larger than the new element, move the element to the next position;
4. Repeat step 3 until you find the position where the sorted element is less than or equal to the new element;
5. After inserting the new element into the position;
6. Repeat steps 2~5.
Animation demo diagram:
OC code:
- (NSArray*)insertionSort:(NSArray*)temArr{
NSMutableArray *arr = [NSMutableArray arrayWithArray: temArr];
NSInteger count = arr.count;
for (int i = 0; i < count; i++) { // number of loops
// Find the appropriate position of arr[i] from the sorted part to insert
for (int j = i; j > 0; j--) { // inner loop
if ([arr[j-1] intValue] > [arr[j] intValue]) {
NSNumber *temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
} else {
// Because the front is sorted, the inner loop can be ended when the comparison condition is not met (it must be greater than the previous value)
break;
}
}
}
return arr;
}
Swift Code:
func insertSort(temArr: [Int] ) -> [Int] {
if temArr.count == 0 {
return []
}
var arr = temArray
let count = arr.count
for i in 0..<count { // number of exchanges
// Find the appropriate position of arr[i] from the sorted part to insert
was j = I
while (j > 0) {
if (arr[j-1] > arr[j] ) {
let temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
} else {
//Because the front is sorted, the inner loop can end as long as the comparison condition is not met, if it is definitely greater than the previous value
break;
}
j-=1;
}
}
return arr
}
4. Shell sort (Shell Sort)
Hill sort is also an insertion sort, which is a more efficient version of the improved simple insertion sort, also known as shrinking incremental sort, and this algorithm is one of the first algorithms to break through O(n2). It differs from insertion sort in that it compares elements that are farther away first
Algorithm description :
1. Select an incremental sequence t1, t2, ..., tk, where ti>tj, tk=1;
2. According to the incremental sequence number k, sort the sequence k times;
3. For each sorting, according to the corresponding increment ti, the column to be sorted is divided into several sub-sequences of length m, and direct insertion sorting is performed on each sub-table. Only when the increment factor is 1, the entire sequence is treated as a table, and the length of the table is the length of the entire sequence.
Animation demo diagram :
OC code:
- (NSArray*)shellSort:(NSArray*)temArr{
NSMutableArray *arr = [NSMutableArray arrayWithArray: temArr];
NSInteger count = arr.count; NSInteger gap = count / 2; //Gap coefficient
while(gap > 0) { // the role of if
for (NSInteger i = gap; i < count; i++) { // Number of passes -- grouping
NSNumber *temp = arr[i];
NSInteger preIndex = i - gap;
while (preIndex >= 0 && [arr[preIndex] intValue] > [temp intValue]) { // determine position exchange
arr[preIndex + gap] = arr[preIndex];
preIndex -= gap;
}
arr[preIndex + gap] = temp;
}
gap /= 2;
}
return arr;
}
Swift Code:
func shellSort(temArr: [Int] ) -> [Int] {
if temArr.count == 0 {
return []
}
var arr = temArray
let count = arr.count
var gap = count / 2 //Gap coefficient
while gap > 0 { // the role of if
for i in gap..<count { // number of times -- grouping
let temp = arr[i]
var preIndex = i - gap
while preIndex >= 0 && arr[preIndex] > temp { // determine position exchange
arr[preIndex + gap] = arr[preIndex]
preIndex -= gap
}
arr[preIndex + gap] = temp
}
gap /= 2
}
return arr
}
5. Select Sort
Selection sorting is an intuitive sorting method, which finds the largest (or smallest) value in turn from the beginning, and transposes the sorted elements. Unsorted elements continue to repeat the sorting operation. until sorted. Double loop time complexity is O(n^2)
Animation demo diagram:
Algorithm process diagram:
OC code:
// data array
NSArray *arr = @[@3,@44, @38, @5, @47, @15, @36, @26, @27, @2, @46, @4, @19, @50, @48];
// method call
NSArray *sortArray = [self selectSort:arr];
NSLog(@"%@",sortArray);
// select sort code
- (NSArray *)selectSort:(NSArray*)temArr{
NSMutableArray *arr = [NSMutableArray arrayWithArray: temArr];
NSInteger count = arr.count;
for (int i = 0; i < count; i++) { // number of exchanges
// First assume that the index of the smallest number is i in each loop
int minIndex = i; // each element is compared with the remaining unsorted elements
for (int j = i + 1; j < count; j++) {
if ([arr[minIndex] intValue] > [arr[j] intValue]) { //find the minimum number
minIndex = j; //save the minimum index
}
}
//After a round of loops, you can find the index of the first minimum value, and then put the minimum value in the position of i
NSNumber *temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
Swift Code:
// array to be sorted
var temArray = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]
// call method
let sortArray = selectSort(temArr: temArray)
// Define selection sort method
func selectSort2(temArr: [Int] ) -> [Int] {
if temArr.count == 0 {
return []
}
var arr = temArray
let count = arr.count
for i in 0..<count {
// number of exchanges
// First assume that the index of the smallest number is i in each loop
var minIndex = i // each element is compared with the remaining unsorted elements
for j in i+1..<count {
if arr[minIndex] > arr[j] { //find the minimum number
minIndex = j // save the minimum index
}
}
//After a round of loops, you can find the index of the first minimum value, and then put the minimum value in the position of i
let temp = arr[i]
arr[i] = arr[minIndex]
arr[minIndex] = temp
}
return arr
}
6. Heap sort
Idea analysis:
The heap is a complete binary tree with the following properties: the value of each node is greater than or equal to the value of its left and right child nodes, called the big top heap; or the value of each node is less than or equal to the value of its left and right child nodes value, known as the small top heap
Big top heap: arr[i] >= arr[2i+1] && arr[i] >= arr[2i+2]
Small top heap: arr[i] <= arr[2i+1] && arr[i] <= arr[2i+2]
The basic idea of heap sorting is : construct the sequence to be sorted into a large top heap, at this time, the maximum value of the entire sequence is the root node at the top of the heap. Swap it with the end element, and the end is the maximum value. Then reconstruct the remaining n-1 elements into a heap, so that the second smallest value of n elements will be obtained. So repeated execution, you can get an ordered sequence
Animation display:
OC code:
- (void)heapSort:(NSMutableArray*)arr{
//1. Build a large top heap
for (NSInteger i = arr.count/2 -1 ; i >= 0; i--) {
//Adjust the structure from the first non-leaf node from bottom to top, from right to left
[self adjustHeap:arr i:i length:arr.count];
}
//2. Adjust the heap structure + exchange the top element and the end element of the heap
for (NSInteger j = arr.count - 1; j > 0; j--) {
//Swap the top element of the heap with the end element
NSNumber *temp = arr[0];
arr[0] = arr[j];
arr[j] = temp;
// readjust the heap
[self adjustHeap:arr i:0 length:j];
}
}
/** Adjust the big top heap (only the adjustment process, based on the construction of the big top heap) */
- (void)adjustHeap:(NSMutableArray*)arr i: (NSInteger)i length: (NSInteger)length{
NSNumber *temp = arr[i];
for (NSInteger k = i*2+1; k < length; k = k*2+1) {
//If the right child is bigger than the do child, point to the right child
if (k+1 < length && [arr[k] intValue]< [arr[k + 1] intValue]) {
k++;
}
//If the largest child is larger than the current node, assign the older child to the current node, modify the current node to be the older child node, and then go down.
if ([arr[k] intValue] > [temp intValue]) {
arr[i] = arr[k];
i = k;
} else {
break;
}
}
//Put temp to final position
arr[i] = temp;
}