數據結構-排序-選擇排序


數據結構-排序-選擇排序



1.算法思想

  • 選擇排序的思想: 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。再從剩餘未排序元素中繼續尋找最小(大)元素,然後放到已排序序列的末尾。重複第二步,直到所有元素均排序完畢。

2.算法複雜度

  • 執行時間: O(n^2)
  • 附加空間: 一個存儲最小記錄的空間
  • 是否是穩定的排序方法: 不穩定

3.算法實現

#include "stdio.h"

#define MAXSIZE 10

typedef int keytype;

typedef struct {
	keytype key;
}recordtyp;

typedef struct {
	int length;
	recordtyp r[MAXSIZE + 1];//多一個是儲存的附加空間
}table;

table * selectsort(table * tab)
{
	int i, j, min_location;  //min_location 是記錄最小排序碼記錄的下標的變量

	//從
	for (i = 1; i <= tab->length - 1; i++)
	{
		min_location = i;
		//從第 i+1 個記錄開始依次比較,更新最小記錄的位置下標
		for (j = i + 1; j <= tab->length; j++)
		{
			//比較當前的記錄和最小記錄的排序碼,如果小於最小記錄就更新最小記錄的下標
			if (tab->r[j].key < tab->r[min_location].key)
			{
				min_location = j;
			}

		}
		//如果最小位置不是第 i 個記錄就進行交換
		if (min_location != i)
		{

			tab->r[0] = tab->r[min_location];
			tab->r[min_location] = tab->r[i];
			tab->r[i] = tab->r[0];
		}
	}
	return tab;
}


table * inputData(table * tab) {

	printf("please input the length:\n");
	scanf("%d", &tab->length);

	printf("please input the data:");
	for (int i = 1; i <= tab->length; i++)
	{
		scanf("%d", &tab->r[i].key);
	}
	return tab;
}

void show(table * tab) {

	printf("the result data:");

	for (int i = 1; i <= tab->length; i++)
	{
		printf("%d ", tab->r[i].key);
	}
}

void main() {
	table * tab = malloc(sizeof(table));
	tab = inputData(tab);
	tab = selectsort(tab);
	show(tab);
}

運行截圖
在這裏插入圖片描述
歡迎大家關注我的博客:breeziness123
轉載說明出處

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章