///by 자바하는놈 #include<stdio.h> #include<string.h> int bubble_sort_char(char str[], size_t size) { if(size <= 1) { return 0; } unsigned int pos; int finished; char temp; pos = 0; while(1) { finished = 1; for(; pos < size-1; pos++) { if(str[pos] > str[pos+1]) { finished = 0; temp = str[pos]; str[pos] = str[pos+1]; str[pos+1] = temp; } } if(finished) { break; } pos++; } printf("%s\n", str); return 0; } int main() { char str[] = "unsorted"; bubble_sort_char(str, strlen(str)); printf("%s\n", str); getchar(); }
Copyrights © - Joinc, All Rights Reserved. Inherited From - Yundream Rebranded By - Joonphil
문제
- 5와 4를 비교 4532가 될것이다. 다음 5와 3을 비교하면 4352가 된다. 마지막으로 5와 2를 비교하면 4325가 된다.
- 다시 4와 3을 비교한다.
- 이를 반복해서 더 이상 비교할게 없을 때, 정렬을 완료한다.
버블소트는 어느정도 정렬이 되어 있는 데이터를 정렬할 때 매우 효율적이다. 그러나 역순으로 정렬되어 있을경우 매우 비효율적이다. 인자로 주어진 문자열을 정렬하는 코드를 만들어보도록 하자///by 자바하는놈 #include<stdio.h> #include<string.h> int bubble_sort_char(char str[], size_t size) { if(size <= 1) { return 0; } unsigned int pos; int finished; char temp; pos = 0; while(1) { finished = 1; for(; pos < size-1; pos++) { if(str[pos] > str[pos+1]) { finished = 0; temp = str[pos]; str[pos] = str[pos+1]; str[pos+1] = temp; } } if(finished) { break; } pos++; } printf("%s\n", str); return 0; } int main() { char str[] = "unsorted"; bubble_sort_char(str, strlen(str)); printf("%s\n", str); getchar(); }Recent Posts
Archive Posts
Tags