選擇排序cpp文件項目結構截圖
項目cpp文件截圖
項目具體代碼截圖
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <string.h>
#include <time.h>
#include <sys/timeb.h>#define MAX 1000
// 獲取當前系統的時間
long getSystemTime() {struct timeb tb;ftime(&tb);return tb.time * 1000 + tb.millitm;
}void PrintArray(int arr[], int length) {for (int i = 0; i < length; i++) {printf("%d ", arr[i]);}printf("\n");
}
void Swap(int* a, int* b) {int temp = *a;*a = *b;*b = temp;
}// 冒泡排序的算法
void BubbleSort(int arr[], int length) {int flag = 0;for (int i = 0; i < length && flag == 0; i++) {flag = 1; // 表示認為已經排序好了for (int j = length - 1; j > i; j--) {if (arr[j - 1] < arr[j]) {// 第二個數比第一個數小交換位置flag = 0;Swap(&arr[j - 1], &arr[j]);}}}}// 選擇排序
void SelectSort(int arr[], int length) {// 選擇排序減少交換次數for (int i = 0; i < length; i++) {int min = i;for (int j = i + 1; j < length; j++) {if (arr[j] < arr[min]) {min = j; // 修改下標}}if (min != i) {Swap(&arr[min], &arr[i]);}}}
int main(void)
{int arr[MAX];int arr2[MAX];srand((unsigned int)time(NULL));for (int i = 0; i < MAX; i++) {int randNum = rand() % MAX;arr[i] = randNum;arr2[i] = randNum;}//冒泡排序long bubbleelect_start = getSystemTime();BubbleSort(arr, MAX);long bubbleelect_end = getSystemTime();printf("冒泡排序%d個元素所需要的時間:%ld\n", MAX, bubbleelect_end - bubbleelect_start);//選擇排序long tselect_start = getSystemTime();SelectSort(arr2, MAX);long teslect_end = getSystemTime();printf("選擇排序%d個元素所需要的時間:%ld\n", MAX, teslect_end - tselect_start);return 0;
}
項目運行結果展示