void quick_sort(int S[], int L, int R)
{
if (L < R)
{
swap(S[L], S[R]);
int i = L, j = R, x = S[L];
while (i < j) {
while (i < j && S[j] >= x)
j--;
if (i < j)
S[i++] = S[j];
while (i < j && S[i] < x)
i++;
if (i < j)
S[j--] = S[i];
S[i] = x;
quick_sort(S, L, i - 1);
quick_sort(S, i + 1, R);
}
}
}
Java版:
package com.sort.QuickSort;
public class QuickSort {
public static void quicksort(int [] array)
{
QSort(array,0,array.length - 1);
}
public static void QSort(int[] array, int low, int high) {
int pivot;
if (low < high)
{
pivot = Partition(array,low,high);
QSort(array,low,pivot - 1);
QSort(array,pivot + 1,high);
}
}
public static int Partition(int[] array, int low, int high) {
int pivotkey;
pivotkey = array[low];
while (low < high)
{
while (low < high && array[high] >= pivotkey)
high--;
swap(array,low,high);
while (low < high && array[low] <= pivotkey)
low++;
swap(array,low,high);
}
return low;
}
public static void swap(int[] array, int low, int high) {
int temp = array[low];
array[low] = array[high];
array[high] = temp;
}
public static void main(String[] args)
{
int [] array = {50,10,90,30,70,40,80,60,20};
QuickSort.quicksort(array);
for (int i = 0;i < array.length;i++)
{
System.out.print(array[i] + " ");
}
}
}
《剑指offer》题目:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路:如果用快速排序解决此题,先排好序,然后检查数组索引为length/2的元素是否出现频率超过了数组长度的一半,超过就满足要求,否则不满足要求,返回零。
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int length = numbers.size();
quick_sort(numbers,0,length - 1);
if (isValid(numbers,numbers[length / 2]))
return numbers[length / 2];
else
return 0;
}
bool isValid(vector<int> numbers,int target)
{
if (numbers.empty())
return false;
int length = numbers.size();
int times = 0;
for (int i = 0;i < length;i++)
{
if (numbers[i] == target)
times++;
}
if (times > length /2)
return true;
return false;
}
void quick_sort(vector<int> S, int L, int R)
{
if (L < R)
{
swap(S[L], S[R]);
int i = L, j = R, x = S[L];
while (i < j) {
while (i < j && S[j] >= x)
j--;
if (i < j)
S[i++] = S[j];
while (i < j && S[i] < x)
i++;
if (i < j)
S[j--] = S[i];
S[i] = x;
quick_sort(S, L, i - 1);
quick_sort(S, i + 1, R);
}
}
}
};
同样,《剑指offer》上相邻的题目:
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4.
这次我直接调用STL函数了:
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> res;
int length = input.size();
if (input.empty() || k > length)
return {};
sort(input.begin(),input.end());
for (int i = 0;i < k;i++)
{
res.push_back(input[i]);
}
return res;
}
};