Objective-C Sorting Algorithm Implementation and objective-c Sorting Algorithm
As a basic skill of programmers, algorithms have always been a tough headache for me. After all, there are very few work contacts with algorithms at ordinary times. Most of the time, they are building UIS, writing business logic, and writing network requests. However, during interviews, algorithms are often the focus of research.
Maybe you will say that you can get these jobs at ordinary times? Indeed, few are used, but you don't. People just don't want you. What do you do ?!
Tang boy has an article about this. I think it is quite good. After reading this article, you may feel it. Http://blog.devtang.com/blog/2015/06/16/talk-about-tech-interview/
Okay. You don't have to talk about it. There is a lot of information about sorting algorithms on the Internet. I sorted out the information and wrote a detailed comment, so that I can see the idea of each algorithm at a glance in the future. If you have any questions, please correct them!
Bubble Sorting
/* Bubble sort * compares two adjacent numbers from the back to the back of each position in the array. If the number is small, switch the positions of the two. * if no data exchange occurs during a traversal, the sorting is completed directly * @ param array */+ (void) bubbleSort :( NSMutableArray *) list {if (list. count <= 1) {return;} int I, y; BOOL bFinish = YES; // whether data exchange occurs for (I = 1; I <= [list count] & bFinish; I ++) {bFinish = NO; // reset the flag for each time, // start from the last bit, compared to the previous one in sequence, if it is small, the switching position // when there is no data exchange during a traversal, it indicates that the sorting has been completed (bFinish = YES ), then the loop for (y = (int) [list count]-1; y> = I; y --) {if ([[list objectAtIndex: y] intValue] <[[list objectAtIndex: Y-1] intValue]) {// exchange location // NSLog (@ "% d <-> % d", [[array objectAtIndex: y-1] intValue], [[array objectAtIndex: y] intValue]); [list exchangeObjectAtIndex: Y-1 withObjectAtIndex: y]; bFinish = YES; // data exchange occurs, continue the next traversal until no data exchange or loop is completed // NSLog (@ "% @", [array componentsJoinedByString: @ ""]); }}}
/*** Bubble sort ** @ param list array to be sorted */+ (void) bubbleSortDesc :( NSMutableArray *) list {if (list. count <= 1) {return;} int I, y; BOOL bFinish = YES; // whether data exchange occurs for (I = 1; I <= [list count] & bFinish; I ++) {bFinish = NO; // reset the flag for each time, // start from the last bit, compared to the previous one in sequence, if it is small, the switching position // when there is no data exchange during a traversal, it indicates that the sorting has been completed (bFinish = YES ), then the loop for (y = (int) [list count]-1; y> = I; y --) {if ([[list objectAtIndex: y] intValue]> [[list objectAtIndex: Y-1] intValue]) {// exchange location // NSLog (@ "% d <-> % d", [[array objectAtIndex: y-1] intValue], [[array objectAtIndex: y] intValue]); [list exchangeObjectAtIndex: Y-1 withObjectAtIndex: y]; bFinish = YES; // data exchange occurs, continue the next traversal until no data exchange or loop is completed // NSLog (@ "% @", [array componentsJoinedByString: @ ""]); }}}
Quick sorting
/*** Quick Sort *** @ param list array */+ (void) quickSort :( NSMutableArray *) list {if (list. count <= 1) {return;} [self quickSort: list startIndex: 0 endIndex: list. count-1];}/*** Quick Sort ** select a data randomly (the first number of arrays is usually used) as the key data, put all the numbers smaller than it in front of it, all the numbers greater than it are placed behind it * and then the data on both sides are sorted quickly * @ param list array * @ param start low index * @ param end High Index */+ (void) quickSort :( NSMutableArray *) list startIndex :( NSInteger) start endIndex :( NSInteger) end {if (start> = end) {// when the low position is greater than the high position, return is sorted ;} NSInteger low = start; NSInteger high = end; NSInteger key = [[list objectAtIndex: start] integerValue]; // take the first number as the key data while (low Insert sort directly
/* ** Insert sort directly * Insert the records to be sorted one by one according to their key code values to an ordered sequence that has already been sorted, until all records are inserted ** @ param list array to be sorted */+ (void) insertionSort :( NSMutableArray *) list {if (list. count <= 1) {return;} // The array is divided into two parts starting from 1st bits: The first part can be regarded as sorted, the last part is unsorted // the data in the last part is traversed in sequence and inserted to the appropriate position in the previous part for (int I = 1; I <list. count; I ++) {int j = I; // Number of unordered parts (1st of unordered parts, the last digit is the last digit of the sorted part. NSInteger temp = [[list objectAtIndex: I] integerValue]; // start from the last digit of the sorted part and push forward. If it is larger than the number to be sorted, move its position back one while (j> 0 & [[list objectAtIndex :( J-1)] integerValue]> temp) {[list replaceObjectAtIndex: j withObject: [list objectAtIndex :( J-1)]; j --;} // After the loop ends, j is the position to be inserted for the number of to be sorted [list replaceObjectAtIndex: j withObject: @ (temp)] ;}}
Binary sorting (insert sorting)
/*** Binary sorting (insert sorting) ** @ param list array to be sorted */+ (void) binaryInsertionSort :( NSMutableArray *) list {if (list. count <= 1) {return;} // The array is divided into two parts starting from 1st bits: The first part can be regarded as sorted, the last part is unsorted // the data in the last part is traversed in sequence and inserted to the appropriate position in the previous part for (int I = 1; I <list. count; I ++) {int left = 0; int right = I-1; int middle; // Number of unordered parts (1st of unordered parts, the last digit is the last digit of the sorted part. NSInteger temp = [[list objectAtIndex: I] integerValue]; while (left <= right) {// compare the number of intermediate positions in the sorted part with middle = (left + right)/2; // if the number is equal to the number to be sorted, insert it directly to this position. if ([[list objectAtIndex: middle] integerValue] = temp) {left = middle; break;} // if it is larger than the number of tasks to be sorted, then search for the intermediate number (next loop) else if ([list objectAtIndex: middle] integerValue]> temp) {right = middle-1 ;} // if the number is smaller than the number to be sorted, query the number in the middle again from the range on the right of the middle position (next loop) else {left = middle + 1 ;}/// the loop ends, locate the left position to be inserted, and move the data on the Right of left (larger than the left position) One for (int j = I; j> left; j --) to the right --) {[list replaceObjectAtIndex: j withObject: [list objectAtIndex: J-1];} // Insert the number of objects to be sorted in the left position [list replaceObjectAtIndex: left withObject: @ (temp)] ;}}
Hill sorting
/* ** Hill sort (insert sort) * First, take a positive integer d1 <n, put all the array elements whose serial numbers are separated by d1 in a group, and insert them in the group for sorting; then take d2 <d1, repeat the preceding grouping and sorting operations until di = 1, that is, all records are sorted in A group until ** @ param list array to be sorted */+ (void) shellInsertionSort :( NSMutableArray *) list {if (list. count <= 1) {return;} NSInteger delt = list. count/2; // increment: the length of the array is half, and the value is halved each time until the increment is 1 NSInteger I; while (delt> = 1) {// directly insert and sort the groups with the position distance = Incremental for (I = delt; I <list. count; I ++) {NSInteger k = I; // number of tasks to be sorted NSInteger temp = [[list objectAtIndex: I] integerValue]; // start from the last digit of the sorted part and push forward (interval = increment) sequentially. If it is larger than the number to be sorted, move its position back to the "incremental" position while (k> = delt & [[list objectAtIndex: k-delt] integerValue]> temp) {[list replaceObjectAtIndex: k withObject: [list objectAtIndex: k-delt]; k-= delt; // incrementally recursive} // The j value after the loop ends is the position of the number to be inserted in the order [list replaceObjectAtIndex: k withObject: @ (temp)];} delt = delt/2; // increment: halved each time }}
Heap sorting
/*** Heap sorting ** utilizes the heap characteristics (the heap top must be the maximum or minimum value ), swap the heap top data with the heap end data (equivalent to deleting the heap top data and saving it to the heap end), and re-construct the heap, until only one data record is left in the heap ** @ param list array to be sorted */+ (void) heapSort :( NSMutableArray *) list {if (list. count <= 1) {return;} NSInteger I; // initialize the heap and obtain the maximum (or minimum) of the parent and left and right subnodes) value as heap top // because the leaf node of heap node I is 2 * I + 1, the initialization starts from the length/2-1 to sort out the heap. count/2-1; I> = 0; I --) {[self heapAdjust: list withIndex: I andLength: list. count];} // NSLog (@ "constructor: % @", [list componentsJoinedByString: @ ""]); // after completing the heap sorting, the 0th bits must be the maximum (or minimum) value. It is equivalent to deleting the 0th bits from the heap by switching to the n-1 bits, then refresh the heap for the remaining data. // perform the preceding switch operation in sequence until only one count is left for (I = list. count-1; I> 0; I --) {[list exchangeObjectAtIndex: 0 withObjectAtIndex: I]; [self heapAdjust: list withIndex: 0 andLength: I]; // NSLog (@ "construct heap: % @", [list componentsJoinedByString: @ ""]) ;}/ *** construct heap (max heap) * ** @ param list: array to be sorted * @ param index: location to be sorted * @ param length: length of the array to be sorted (here, because the data to be sorted and the sorted data share array) */+ (void) heapAdjust :( NSMutableArray *) list withIndex :( NSInteger) index andLength :( NSInteger) length {// left subnode, the right child node is lchild + 1 NSInteger lchild = index * 2 + 1; while (lchild <length) {// you can determine whether the right child node exists, if yes, determine whether the right subnode is larger than the left node, if it is larger than the left node, use the right child node to compare the if (lchild + 1 <length & [[list objectAtIndex: lchild + 1] integerValue]> [[list objectAtIndex: lchild] integerValue]) {lchild ++; // ++ indicates moving the left node to the right node, for the following comparison with the parent node} // if the parent node is smaller than the child node, it indicates that it is itself a heap and you do not need to sort it out if ([list objectAtIndex: lchild] integerValue] <[[list objectAtIndex: index] integerValue]) {break;} // exchange the values of the Parent and Child Nodes (sink the parent node) [list exchangeObjectAtIndex: index withObjectAtIndex: lchild]; // sink the parent node to the child node, and continue to sort out the following heap index = lchild; lchild = index * 2 + 1 ;}}
Select sort
/* ** Select sort * select the smallest (or largest) element from the data elements to be sorted at the starting position of the sequence, until all the data elements to be sorted are arranged ** @ param list array to be sorted */+ (void) selectSort :( NSMutableArray *) list {if (list. count <= 1) {return;} NSInteger I, j; // sort from 0th bits until the last bits (the last BITs do not need to be sorted) for (I = 0; I <list. count-1; I ++) {j = I; // record the current position as the key element of the comparison. // traverse the subsequent element for (NSInteger k = I + 1; k <list. count; k ++) {// if the element is smaller than the key element, point the key element to this position and traverse if ([list objectAtIndex: k] integerValue] <[[l Ist objectAtIndex: j] integerValue]) {j = k ;}// obtain the smallest element position j after the traversal ends. If it is not the initial position, if (I! = J) {[list exchangeObjectAtIndex: I withObjectAtIndex: j] ;}}
Merge Sorting
/***** Merge and sort the array into two parts, so that both the left and right parts are ordered and then merged into one * in order to make both the left and right parts orderly, the recursive method can be used, split it until there is only one element left after the split, which can be regarded as ordered, and then merge the left and right parts, take 0th numbers from the two parts for comparison, save the smaller (or larger) number to the temporary array, and then compare it with the larger one in the previous comparison, until one side has no data, copy the remaining number in the other side to the temporary array * The final generated temporary array is the sorted result ** @ param list array to be sorted */+ (void) mergeSort :( NSMutableArray *) list {if (list. count <= 1) {return;} [self mergeSort: list startIndex: 0 endIndex: list. count-1] ;}+ (void) mergeSort :( NSMutableArray *) list startIndex :( NSInteger) startIndex endIndex :( NSInteger) endIndex {if (startIndex <endIndex) {// obtain the intermediate position, recursively merge the left and right sides until there is only one NSInteger middle = (startIndex + endIndex)/2; [self mergeSort: list startIndex: startIndex endIndex: middle]; [self mergeSort: list startIndex: middle + 1 endIndex: endIndex]; // merge the data on the left and right sides of NSInteger I = startIndex; // NSInteger j = middle + 1; // NSMutableArray * temp = [NSMutableArray array]; // temporary array while (I <= middle & j <= endIndex) {// If the left data is small, put it in the temporary array, move one if ([[list objectAtIndex: I] integerValue] <[list objectAtIndex: j] integerValue]) {[temp addObject: [list objectAtIndex: i]; I ++;} // otherwise, place the right data in a temporary array and move the right position to the back of an else {[temp addObject: [list objectAtIndex: j]; j ++ ;}/// if there is data on the left, copy all the remaining parts to the temporary array while (I <= middle) {[temp addObject: [list objectAtIndex: I]; I ++;} // if there is still data on the right side (only the left and right sides may have data on one side ), copy all the remaining parts to the temporary array. while (j <= endIndex) {[temp addObject: [list objectAtIndex: j]; j ++ ;} // Save the data in the temporary array (sorted) to the original data to sort the original data for (I = 0; I <temp. count; I ++) {// Note: You need to start from the startIndex position, because here is the recursively called [list replaceObjectAtIndex: startIndex withObject: [temp objectAtIndex: I]; startIndex ++ ;}}}