对了,那个第四个问题有O(N)的解法,是快速选择的思想 下面是我实现的代码 #include <iostream> using namespace std; #define MAX_SIZE 2001 //int a[2001]; void swap(int *a, int *b) {  int tmp = *a;  *a = *b;  *b = tmp; } int partition(int a[], int low, int high) {  int privotKey = a[low];                             //基准元素   while (low < high){                                   //从表的两端交替地向中间扫描    while (low < high  && a[high] >= privotKey) --high;  //从high 所指位置向前搜索,至多到low+1 位置。将比基准元素小的交换到低端    swap(&a[low], &a[high]);   while (low < high  && a[low] <= privotKey) ++low;   swap(&a[low], &a[high]);  }  //a[low] = privotKey;  return low; } void Top100(int a[], int k,int start,int end){  int i = start;  int j = end - 1;  int index = partition(a, i, j);  while (index!=end-k-1)  //数组后100  {   if (index<end - k - 1)   {    i = ++index;    index = partition(a, i, j);   }   else   {    j = index;    index = partition(a, i, j);   }  } } int main() {  int a[] = { 1111, 22222, 3333, 4, 5, 6, 7, 8,9 ,10};  Top100(a, 3, 0, 10);  for (int i = 0; i <10 ; i++)  {   cout << a[i]<<endl;  }  return 0; }
点赞 1

相关推荐

牛客网
牛客企业服务