选择排序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;
}
项目运行结果展示