首先排序还是一样的排序(冒泡,插入,选择,快速,折半查找,数组打乱,),今天主要看看在oc中如何实现几种排序;
还是上代码吧:
首先要在.h文件中写声明:
void printArray(const int array[], int count);
void swap(int *p1, int *p2);
void bubbleSort(int array[], int count);
void selectionSort(int array[], int count);
void insertionSort(int array[], int count);
void breakArray(int array[], int count);
int halfSeek(const int array[], int count, int target);
void quickSork(int array[], int const);
void printArray(const int array[], int count)
{
for (int i = 0; i < count; i++) {
printf("[%2d] : %d\n", i, array[i]);
}
}
void swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void bubbleSort(int array[], int count)
{
int flag = 0;
for (int i = 0; i < count - 1 && flag == 0; i++) {
int flag = 1;
for (int j = 0; j < count - i - 1; j++) {
if (array[j] > array[j + 1]) {
swap(array + j, array + j + 1);
flag = 0;
}
}
}
}
void selectionSort(int array[], int count)
{
for (int i = 0; i < count - 1; i++) {
int minIndex = i;
for (int j = minIndex + 1; j < count; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(array + minIndex, array + i);
}
}
}
void insertionSort(int array[], int count)
{
for (int i = 1; i < count; i++) {
int j = i;
int temp = array[j];
while (j > 0 && array[j - 1] > temp) {
array[j] = array[j - 1];
j--;
}
array[j] =temp;
}
}
void breakArray(int array[], int count)
{
for (int i = count - 1; i > 0; i--) {
unsigned int random = arc4random() % (i + 1);
swap(array + random, array + i);
}
}
int halfSeek(const int array[], int count, int target)
{
int start = 0, end = count - 1, mid = 0;
while (start <= end) {
mid = (start + end) / 2;
if (array[mid] > target) {
end = mid - 1;
} else if(array[mid] < target){
start = mid + 1;
} else {
return mid;
}
}
return -1;
}
void quickSork(int array[], int count)
{
if(count < 2){
return;
}
int start = 0, end = count - 1;
int temp = array[start];
while (start < end) {
while(start < end && array[end] > temp){
end--;
}
if (start < end) {
array[start] = array[end];
start++;
}
if (start < end && array[start] < temp) {
start++;
}
if (start < end) {
array[end] = array[start];
end--;
}
}
array[start] = temp;
quickSork(array, start);
quickSork(array + start + 1, count - start - 1);
}
最后在main.m里实现就行了:
int array[] = {3, 5, 1, 7, 2, 9, 4, 8, 6, 7};
int count = sizeof(array) / sizeof(*array);
printArray(array, count);
int a = 3, b = 4;
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
bubbleSort(array, count);
printArray(array, count);
selectionSort(array, count);
printArray(array, count);
insertionSort(array, count);
printArray(array, count);
breakArray(array, count);
printArray(array, count);
int array[] = {1, 2, 3, 4, 5, 6, 7};
int count = sizeof(array) / sizeof(*array);
printf("%d\n",halfSeek(array, count, 5));
总之,和之前c的排序一样,只是改变了写方法的位置,其他的变化不大.