冒泡排序/選擇排序/插入排序(C語言版實現)

交換函數

// 交換倆個指針對應的值
int swap(int *x,int *y){
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
}

冒泡排序

// 冒泡排序
void bubbleSort(int *array,int n){
	puts("bubbleSort");
	int i,j,isSorted;

	for (i = 0; i < n-1; i++){
		isSorted = 1;
		for(j = 0; j < n-1-i;j++){
			//if (array[j] > array[j+1]){
			if (*(array+j) > *(array+j+1)){
				// 調用交換函數,傳入倆個值的指針
				swap(array+j,array+j+1);
				isSorted = 0;
			} 
		}

		// 如果沒有交換過,意味着後面的樹是有序的,直接跳出外層循環
		if (isSorted){
			break;
		}
	}
} 

插入排序

void insertSort(int *array,int n){
	puts("insertSort");
	int i,j;
	for (i = 1; i < n; i++){
		for (j = i; j > 0;j--){
			int *x = array+j;
			int *y = array+j-1;
			if (*x < *y){
				swap(x,y);
			} else {
				break;
			}
		}
	}
}

選擇排序

// 選擇排序 n爲數組的元素個數
// 不穩定 
void select_sort(int *array,int n){
	puts("select_sort");
	int i,j,temp;
	// 初始化指針
	int *minIndex = NULL;
	for (i = 0; i < n-1; i++){
		// 將最小指針指向開頭的元素
		minIndex = array+i;
		for (j = i+1; j < n; j++){
			if (*minIndex > *(array+j)){
				minIndex = array + j;
			}
		}

		if (minIndex != array+i){
			swap(minIndex,array+i);
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章