- (NSString *)reorderString:(NSString *)originalStr{ int length = [originalStr length]; int sizeChar; if (length < 12) { sizeChar = length; } else { sizeChar = length; } unichar wordChar; char *wordsChar = (char *)malloc(sizeof(char)*length); //char *wordsUnichar; for (int i = 1; i <= length; i++) { wordChar = [originalStr characterAtIndex:(i-1)]; wordsChar[i] = wordChar; } quickSort(wordsChar, 0, length); NSString* result = [[NSString alloc] initWithCString:wordsChar]; free(wordsChar); // for(int j = 1; j <= length; j++) { // wordChar = wordsChar[j]; // NSLog(@"%c", wordChar); // wordsChar[j] = 0; // } return result; }
下面是快速排序:
#import "CommomUitl.h" @implementation CommomUitl void swapV(char *a, char *b){ char temp; temp = *a; *a = *b; *b = temp; } int partitions(char originalStr[], int low, int high){ char temp= originalStr[low]; int i=low,j=high; while(i<j) { while( (originalStr[j] >= temp) && (i<j) ) j--; if(i<j) { swapV(&originalStr[i], &originalStr[j]); i++; } while( ( originalStr[i] <= temp ) && (i<j) ) i++; if(i<j) { swapV(&originalStr[i], &originalStr[j]); j--; } } return i; } void quickSort(char originalStr[], int low, int high){ int pos; if(low < high) { pos=partitions(originalStr,low,high); quickSort(originalStr,low,pos-1); quickSort(originalStr,pos+1,high); } } @end
输入字符串"iteye"
则输出"eeity"
总结:注意点一,动态分配数组和手动释放
注意点二,数组下标是否越界,以及开始下标值
堆与栈
以数组的方式申请空间时,由系统管理,其作用域结束则释放;在内存中为连续的,以栈方式存在
malloc方式申请空间,由程序员自己控制;需自己手动free,否则一直存在内存中;在内存中以堆的形式存在,非连续。