Created
October 26, 2010 13:33
-
-
Save VoQn/646896 to your computer and use it in GitHub Desktop.
ポインタを使った挿入ソート(アルゴリズムクイックリファレンス p71)
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
// -*- mode:c; coding:utf-8; -*- | |
// INSERTION SORT PROGRAM | |
// | |
// <ORDER> | |
// BEST: O(n) | |
// AVERAGE: O(n^2) | |
// WORST: O(n^2) | |
#include <stdio.h> | |
#include <stdlib.h> | |
/* Prototype */ | |
int cmp (const void *, const void *); | |
void sortPointers(void **ar, int n, int(*cmp)(const void *, const void *)); | |
/* Main */ | |
int main (int argc, char *argv[]) { | |
if (argc < 2) { | |
fprintf(stderr, "This Program need more than 2 arguments."); | |
return 0; | |
} | |
char *elem[argc-1]; | |
int k; | |
for(k = 0; k < argc - 1; k++){ | |
elem[k] = argv[k + 1]; | |
} | |
sortPointers(elem, argc-1, *cmp); | |
int i; | |
for(i = 0; i < argc - 1; i++){ | |
printf("%s ", elem[k]); | |
} | |
return 0; | |
} | |
int cmp (const void *p, const void *q) { | |
double p_val = atof((char *)p), q_val = atof((char *)q); | |
return (p_val == q_val) ? 0 : (p_val < q_val) ? -1 : 1; | |
} | |
void sortPointers (void **ar, int n, int(*cmp)(const void *,const void *)) { | |
int j; | |
for(j = 1; j < n; j++) { | |
int i = j - 1; | |
void *value = ar[j]; | |
while (i >= 0 && cmp(ar[i], value) > 0) { | |
ar[i + 1] = ar [i]; | |
i--; | |
} | |
ar[i + 1] = value; | |
} | |
} | |
// EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment