Last active
September 4, 2015 05:50
-
-
Save gomasy/aed0b7788f585c888f5e to your computer and use it in GitHub Desktop.
bubble sort
This file contains hidden or 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
#include <stdio.h> | |
#include <stdlib.h> | |
void gen_ary(int ary[], int size); | |
void shuffle(int ary[], int size); | |
void sort(int ary[], int size); | |
int main() { | |
int i, size; | |
scanf("%d", &size); | |
int ary[size]; | |
gen_ary(ary, size); | |
shuffle(ary, size); | |
sort(ary, size); | |
return 0; | |
} | |
void gen_ary(int ary[], int size) { | |
int i; | |
for (i = 1; i <= size; i++) { | |
ary[i] = i; | |
} | |
} | |
void shuffle(int ary[], int size) { | |
int i; | |
for (i = 1; i <= size + 1; i++) { | |
int j = rand() % size; | |
int t = ary[i]; | |
ary[i] = ary[j]; | |
ary[j] = t; | |
} | |
} | |
void sort(int ary[], int size) { | |
int i, j = 0, k = 0, flg = 0; | |
while (!flg) { | |
int rep = 0; | |
j++; | |
printf("Phase %d: [", j); | |
for (i = 1; i <= size; i++) { | |
if (ary[i] > ary[i + 1]) { | |
int l = ary[i]; | |
ary[i] = ary[i + 1]; | |
ary[i + 1] = l; | |
rep = 1; | |
k++; | |
} | |
if (i != 1) { | |
printf(", %d", ary[i]); | |
} else { | |
printf("%d", ary[i]); | |
} | |
} | |
printf("]\n"); | |
if (!rep) { | |
flg = 1; | |
} | |
} | |
printf("\n総比較回数: %d\n総置換回数: %d\n", j, k); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment