Find the smallest k elements

Question:
Find the smallest k elements
Answer:
void findkmin(int *array, int len, int k) {
  int* kmin = new int[k];
  if (len <= k) {
    for (int i = 0; i < len; i++)
      kmin[i] = array[i];
  }
  else {
    for (int i = 0; i < len; i++) {
      int j;
      for (j = 0; j < ((i < k) ? i : k); j++) {
        if (kmin[j] > array[i])
          break;
      }
      if (j < k) {
        for (int m = k-1; m > j; m--)
          kmin[m] = kmin[m-1];
        kmin[j] = array[i];
      }
    }
  }
  for (int i = 0; i < k; i++)
    cout << kmin[i] << " ";
  cout << endl;
  delete [] kmin;
}

Comments

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)