1.递归实现
1.1C语言
#include <stdio.h>
void swap(int v[], int left, int right)
{
int temp = v[left];
v[left] = v[right];
v[right] = temp;
}
void qsort(int v[], int left, int right)
{
int i, last;
//void swap(int v[], int i, int j);
if (left >= right)
return;
swap(v, left, (left + right) / 2);
last = left;
for (i = left + 1; i <= right; i++)
if (v[i]<v[left])
swap(v, ++last, i);
swap(v, left, last);
qsort(v, left, last - 1);
qsort(v, last + 1, right);
}
void quick2Sort(int v[], int left, int right)
{
//void swap(int v[], int left, int right);
int i, last;
if (left >= right)
return ;
swap(v, left, (left + right) / 2);
last = left;
for (i = left+1; i <= right; i++)
if (v[i] < v[left])
swap(v, ++last,i );
swap(v, left, last);
quick2Sort(v,left,last-1);
quick2Sort(v, last + 1,right);
}
int main()
{
//void swap(int v[], int left, int right);
//void quickSort(int v[], int left, int right);
int count2;
int n = 0;
int v[4];
int i = 0;
int v2[6] = { 9,8,7,6,5,3 };
int count = 0;
printf("Hello World!\n");
while (1)
{
scanf("%d", &v[i++]);
if (getchar() == '\n')
break;
}
printf("you have input:%d\n",i);
count = i;
count2 = i - 1;
for (i = 0; i < 6; i++)
printf("%d ", v2[i]);
quick2Sort(v2, 0, 5);
//qsort(v2, 0, 5);
for (i = 0; i < 6; i++)
printf("%d ", v2[i]);
//scanf("%d", &n);
//printf("%d\n", n);
return 0;
}
1.2 C++实现
#include <iostream>
#include <vector>
//#include <functional>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
void swap(vector<int>& v,int left,int right)
{
int temp =v[left];
v[left] = v[right];
v[right] = temp;
}
void quick_Sort(vector<int>& v,int left,int right)
{
int i, last;
if (left >= right)
return;
swap(v, left, (left + right) / 2);
last = left;
for (i = left; i <= right; i++)
if (v[i] < v[left])
swap(v,++last,i);
swap(v, left, last);
quick_Sort(v,left,last-1);
quick_Sort(v,last+1,right);
//printf("in\n");
}
vector<int> stringToIntegerVector(string input) {
vector<int> output;
//trimLeftTrailingSpaces(input);
//trimRightTrailingSpaces(input);
//input = input.substr(1, input.length() - 2);
stringstream ss;
ss.str(input);
string item;
char delim = ' ';
while (getline(ss, item, delim)) {
output.push_back(stoi(item));
}
return output;
}
int main()
{
int n = 0;
printf("Hello World! 12\n");
string line;
getline(cin,line);
vector<int> v = stringToIntegerVector(line);
for (auto i : v) {
printf(" %d ",i);
}
printf("\n");
quick_Sort(v, 0, v.size() - 1);
//sort(v.begin(), v.end());
for (auto i : v) {
printf(" %d ", i);
}
printf("\n");
//scanf("%d",&n);
//printf("%d\n",n);
return 0;
}