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;
}

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe