pragma mark 選擇-冒泡排序優(yōu)化
pragma mark 概念
pragma mark 代碼
#include <stdio.h>
void bubbleSort(int nums[], int length); // 冒泡
void selectSort(int nums[], int length); // 選擇
void printArray(int nums[],int length);
//void swap(int v1,int v2);
void swap(int nums[],int i, int j);
int main()
{
#pragma mark 選擇函數(shù)
//已知一個(gè)無(wú)序的數(shù)組,里面有5個(gè)元素,要求對(duì)數(shù)組進(jìn)行排序
int nums[5] = {99,12,88,11,22};
#pragma mark 計(jì)算
int length = sizeof(nums) / sizeof(nums[0]);
#pragma mark 排序前
// for (int i = 0; i < length - 1; i++) {
// printf("排序前 nums[%i] = %i\n",i, nums[i]);
// }
printArray(nums, length);
// selectSort(nums,length);
bubbleSort(nums,length);
printf("-----------------------------\n");
printArray(nums, length);
// 排序后
// printf("-----------------------------\n");
// for (int i = 0; i < length - 1; i++) {
// printf("nums[%i] = %i\n",i, nums[i]);
// }
return 0;
}
// 遍歷數(shù)組
#pragma mark 遍歷數(shù)組
void printArray(int nums[],int length)
{
for (int i = 0; i < length - 1; i++) {
printf("nums[%i] = %i\n",i, nums[i]);
}
}
#pragma mark 選擇排序
void selectSort(int nums[], int length)
{
// 取出數(shù)比較 交換兩個(gè)數(shù)
for (int i = 0; i < length - 1 ; i++) {
for (int j = i; j< length - 1; j++) {
if (nums[i] > nums[j]) {
/*
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
*/
// swap(nums[i],nums[j]);
swap(nums, i, j);
}
}
}
}
void bubbleSort(int nums[], int length)
{
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++) {
if (nums[j]>nums[j+1]) {
swap(nums, j, j+1);
}
}
}
}
#pragma mark 交換變量
// 基本數(shù)據(jù)類型作為函數(shù)的參數(shù),是值傳遞,在函數(shù)中修改形參不會(huì)影響實(shí)參的值
/*
void swap(int v1,int v2)
{
int temp = v1;
v1 = v2;
v2 = temp;
}
*/
void swap(int nums[],int i, int j)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
OC代碼排序
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
NSArray *arr = @[@1,@99,@33,@55,@77];
NSLog(@"%@",arr);
arr = [arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@",arr);
return 0;
}