selection problem/排序算法

来源:互联网 发布:淘宝店刚开始卖什么好 编辑:程序博客网 时间:2024/06/11 17:20

Suppose you have a group of n numbers and would like to determine the kth largest. This is known as the selection problem.


1. bubble sort/冒泡法

One way to solve this problem would be to read the n numbers into an array, sort the array in decreasing order by somesimple algorithm such as bubblesort, and then return the element in position k.


#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main() {
// 100 random data
int src_data[100];
printf("Display the sourc data\n");

srand(time(NULL));                 // random seed
for (int i = 0; i < 100; i++)
{
src_data[i] = 1+(int)99 * rand() / (RAND_MAX + 1); // random data from 1 to 100
printf("%d\n", src_data[i]);
}

// bubble sort approach
int temp;
for(int m=0;m<100;m++)
for (int n = 0; n < 100-m-1; n++) {
if (src_data[n] > src_data[n+1]) {
temp = src_data[n];
src_data[n] = src_data[n+1];
src_data[n+1] = temp;
}
}
printf("\nDisplay the bubble sort data\n");
for (int k = 0; k < 100; k++) 
printf("%d\n", src_data[k]);

return -1;
}

原创粉丝点击