Title Description:
Given an unordered array of integers, returns the small number of k in this array.
Analytical:
The most common idea is to sort the array, the quickest sort is the fast row, and then return the number of K of the sorted array, the algorithm time complexity is O (NLOGN), the space complexity is O (1). Use the idea of a fast line, but recursively only half of the array after patition, so that the time complexity will be O (n).
In the "Introduction to the algorithm" has a detailed description of the main use of C + + implementation, the idea is to select the first number of the current array as "spindle", the following all the numbers into two parts, the front part is smaller than the "spindle", the latter part is larger than the "spindle", and then calculate the number of the previous part If greater than k recursion--in the previous section to find the number of K, if less than K in the later part of the search, at this time k to update K need to subtract the number of the first part of the number, recursive lookup. Recursive details of their own grasp the following on the line, the basic idea is this.
Code implementation:
#include <iostream> #include <string> #include <cstring> #include <vector> #include < Algorithm>using namespace std;/* Title Description: Given an unordered array of integers, returns the small number of k in this array. Realize the idea: is to select the first number of the current array as the "spindle", the following all the numbers into two parts, the front part is less than the "spindle", the latter part is greater than the "spindle", and then calculate the number of the previous part of the numbers, if greater than k recursive--in the previous section to find the number of If less than k in the later part of the search, at this time k to update K need to subtract the number of the first part of the number, recursively find */void swap (int *p, int *q) {int t; t = *p; *p = *q; *q = t;} int Findnumberk (vector<int> &vec, int k, int s, int e)//Quick Sort (method of binary narrowing recursion interval) find the k{int roll = Vec[s], be = 0 , j = s; for (int i = s+1; i<= e, i++) {if (Vec[i] < roll) {j + +; Swap (&vec[i], &vec[j]); be++; }} swap (&vec[s], &vec[j]); if (be = = k-1) return roll; else if (be < k-1) {return Findnumberk (VEC, K-be-1, J + 1, E); } else return Findnumberk (VEC, K, S, j-1);} int main () {vector<int> A; int temp, k; cout << "input data:" << Endl CIN >> Temp; while (temp! = 0) {a.push_back (temp); CIN >> Temp; } cout << "input K:" << Endl; Cin >> K; int number = Findnumberk (A, K, 0, A.size ()-1); cout << "Test Result:" << number<< Endl; /* The next use sort template quick row for results validation */Sort (A.begin (), A.end (), less<int> ()); cout << "real Result:" << a[k-1] << Endl; return 0;}
Execution Result:
Introduction to Algorithms: Quickly find out the small number of K in an unordered array