- (void)viewDidLoad {
[super viewDidLoad];
int array[] = {1,2,12,31,43,11,2,3,76,23,98};
int count = sizeof(array) / sizeof(array[1]);
// bubbleFunc(array, count);
// selectedFunc(array,count);
// insertFunc(array,count);
shellSort(array,count);
for (int i=0; i<count; i++) {
NSLog(@"%ld",array[i]);
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
void bubbleFunc(int* array, int count) {
int i,j,temp;
for (i=0; i<count-1; i++) {
for (j=0; j<count-1-i;j++) {
if (array[j]<array[j+1]) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
void selectedFunc (int *array, int count) {
int i,j,maxIndex,temp;
for (i=0;i<count-1;i++) {
maxIndex = i;
for (j=i+1;j<count;j++) {
if (array[maxIndex]<array[j]) {
maxIndex = j;
}
}
temp = array[maxIndex];
array[maxIndex] = array[i];
array[i] = temp;
}
}
void insertFunc (int *array, int count) {
int i,j,temp;
for (i=1;i<count;i++) {
if (array[i] < array[i-1]) {
temp = array[i];
for (j=i-1;j>=0 && array[j]>temp;j--) {
array[j+1] = array[j];
}
array[j+1] = temp;
}
}
}
void shellSort(int *array, int count) {
//希尔排序可以理解为将一个大数组按照间隔inc分为inc个小数组
//每个数组按照直接插入排序进行处理
int inc =count;
int i,j,tmp = 0;
do{
inc = inc/4 + 1;
for(i=inc;i<count;i++){
if(array[i] < array[i-inc]){
tmp = array[i];
for(j=i-inc;j>=0 && tmp < array[j]; j-=inc){
array[j+inc] = array[j];
}
array[j+inc] = tmp;
}
}
}
while(inc>1);
}
@end
网友评论