Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

문제

정렬알고리즘 중 퀵소트(:12)다음으로 간단하다고 생각되는 알고리즘이다. 원리는 인접한 배열의 요소를 비교/교환한다음에 전체적으로 대충 정렬을 하면서 최대값의 배열을 제일 마지막으로 보내는 것을 반복한다.

만약 5432가 있다면
  1. 5와 4를 비교 4532가 될것이다. 다음 5와 3을 비교하면 4352가 된다. 마지막으로 5와 2를 비교하면 4325가 된다.
  2. 다시 4와 3을 비교한다.
  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();
}