Created
December 7, 2014 09:04
-
-
Save Jamesits/a184f2e3b42aa21e5681 to your computer and use it in GitHub Desktop.
对大小为 10 的 int 数组进行绝对值从小到大排序。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//#define USE_QSORT | |
// 上面一行取消注释就调用 C 自带的快速排序算法,否则使用手写的冒泡排序 | |
#include <stdio.h> | |
#include <stdlib.h> | |
int iabs(int a) | |
{ | |
return a > 0 ? a : -a; | |
} | |
#ifdef USE_QSORT | |
int comp(const void *a, const void *b) | |
{ | |
return iabs(*(int *)a) - iabs(*(int *)b); | |
} | |
void abs_sort(int *ptr, size_t size) | |
{ | |
qsort(ptr, size, sizeof(int), comp); | |
} | |
#endif | |
#ifndef USE_QSORT | |
void swap(int *a, int *b) | |
{ | |
int t; | |
t = *a; | |
*a = *b; | |
*b = t; | |
} | |
void abs_sort(int *ptr, size_t size) | |
{ | |
int i, j; | |
for (i = size - 1; i >= 0; i--) | |
{ | |
for (j = 0; j < i; j++) | |
{ | |
if (iabs(ptr[j]) > iabs(ptr[j+1])) swap(ptr + j, ptr + j + 1); | |
} | |
} | |
} | |
#endif | |
int main() | |
{ | |
int a[10], i; | |
for (i = 0; i < 10; i++) | |
{ | |
scanf("%d", &a[i]); | |
} | |
abs_sort(a, 10); | |
for (i = 0; i < 10; i++) | |
{ | |
printf("%d ", a[i]); | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment