标签:
1. Quick Sort:
int partition(int A[], int p, int r) { int x = A[r]; // Pivot element int i = p - 1; // Index of last element that not larger than pivot element for(int j = p; j < r; ++j) { if(A[j] <= x) { ++i; exchange(A[i], A[j]); } } exchange(A[i+1], A[r]); return i+1; } void quickSort(int A[], int p, int r) { if(p >= r) return; int q = partition(A, p, r); quickSort(A, p, q - 1); quickSort(A, q + 1, r); }
2. Search in Rotated Array:
class Solution { int comp(int A[], int s, int e, int target){ if(s > e) return -1; if(s == e) return (A[s] == target ? s : -1); int mid = s + (e - s) / 2; if(A[mid] == target) return mid; else if(A[mid] > target){ // if first part is not rotated if(A[mid] >= A[s]){ if(target >= A[s]) return comp(A, s, mid-1, target); else return comp(A, mid+1, e, target); }else{ return comp(A, s, mid-1, target); } }else{ // if first part is not rotated if(A[mid] >= A[s]){ return comp(A, mid+1, e, target); }else{ if(target <= A[e]) return comp(A, mid+1, e, target); else return comp(A, s, mid-1, target); } } } public: int search(int A[], int n, int target) { return comp(A, 0, n - 1, target); } };
3. Maximum Subarray:
class Solution { public: int maxSubArray(int A[], int n) { int dp = A[0]; int end = dp; for(int i = 1; i < n; ++i){ end = end > 0 ? end + A[i] : A[i]; dp = dp > end ? dp : end; } return dp; } };
标签:
原文地址:http://www.cnblogs.com/kid551/p/4307322.html