给定一组数据,划分为两个集合,集合内元素个数分别为n1,n2,元素和为s1,s2,使|n1-n2|最小且|s1-s2|最大。
法一:全部快排,时间复杂度O(nlogn),空间复杂度O(1)
法二:部分快排,递归方式。
法三:部分快排,非递归方式。时间复杂度O(n),空间复杂度O(1)
#include <stdio.h>
void printfArray(int array[],int length){
for(int i=0;i<length;i++){
printf("%d ",array[i]);
}
printf("\n");
}
int partition(int array[],int i,int j){
int x=array[i];
while(i<j){
while(i<j&&array[j]>=x){
j--;
}
if(i<j){
array[i]=array[j];
i++;
}
while(i<j&&array[i]<=x)
i++;
if(i<j){
array[j]=array[i];
j--;
}
}
array[i]=x;
return i;
}
void quicksort(int array[],int i,int j){
if(i<j){
int index=partition(array,i,j);
printfArray(array,8);
quicksort(array,i,index-1);
quicksort(array,index+1,j);
}
}
int main(){
int array[]={0,-1,-2,0,-10,3,-4,1};
quicksort(array,0,7);
printfArray(array,8);
int s1=0,s2=0;
for(int i=0;i<4;i++){
printf("%d ",array[i]);
s1+=array[i];
}
printf("\n");
for(int i=4;i<8;i++){
printf("%d ",array[i]);
s2+=array[i];
}
printf("\n");
printf("%d\n",s2-s1);
return 0;
}
运算结果:
-4 -1 -2 0 -10 0 3 1
-10 -4 -2 0 -1 0 3 1
-10 -4 -2 0 -1 0 3 1
-10 -4 -2 -1 0 0 3 1
-10 -4 -2 -1 0 0 1 3
-10 -4 -2 -1 0 0 1 3
-10 -4 -2 -1
0 0 1 3
21
Program ended with exit code: 0
#include <stdio.h>
void printfArray(int array[],int length){
for(int i=0;i<length;i++){
printf("%d ",array[i]);
}
printf("\n");
}
int partition(int array[],int i,int j){
int x=array[i];
while(i<j){
while(i<j&&array[j]>=x){
j--;
}
if(i<j){
array[i]=array[j];
i++;
}
while(i<j&&array[i]<=x)
i++;
if(i<j){
array[j]=array[i];
j--;
}
}
array[i]=x;
return i;
}
void quicksort(int array[],int i,int j,int mid){
if(i<j){
int index=partition(array,i,j);
printfArray(array,8);
if(index==mid)return;
if(index>mid) quicksort(array,i,index-1,mid);
if(index<mid) quicksort(array,index+1,j,mid);
}
}
int main(){
int array[]={0,-1,-2,0,-10,3,-4,1};
quicksort(array,0,7,4);
printfArray(array,8);
int s1=0,s2=0;
for(int i=0;i<4;i++){
printf("%d ",array[i]);
s1+=array[i];
}
printf("\n");
for(int i=4;i<8;i++){
printf("%d ",array[i]);
s2+=array[i];
}
printf("\n");
printf("%d\n",s2-s1);
return 0;
}
运算结果:
-4 -1 -2 0 -10 0 3 1
-10 -4 -2 0 -1 0 3 1
-10 -4 -2 0 -1 0 3 1
-10 -4 -2 -1 0 0 3 1
-10 -4 -2 -1 0 0 3 1
-10 -4 -2 -1
0 0 3 1
21
Program ended with exit code: 0
#include <stdio.h>
void swap(int a,int b){
int t;
t=a;
a=b;
b=t;
}
void printfArray(int a[],int length){
for(int i=0;i<length;i++){
printf("%d ",a[i]);
}
printf("\n");
}
void quicksort(int a[],int n,int low,int high)
{
int flag=1;
int k=4;//中间值
while(flag)
{
int i=low;
int p=a[low];
for(int j=low+1;j<=high;j++){
if(a[j]<p){
swap(a[++i],a[j]);
}
}
swap(a[i],a[low]);//快排
for(int m=0;m<=high;m++){
printf("%d ",a[m]);
}
printf("\n");
if(i==k) flag=0;
else if(i<k) low=i+1;
else high=i-1;
}
}
int main(){
int a[]={0,-1,-2,0,-10,3,-4,1};
quicksort(a,8,0,7);
printfArray(a,8);
int s1=0,s2=0;
for(int i=0;i<4;i++){
printf("%d ",a[i]);
s1+=a[i];
}
printf("\n");
for(int i=4;i<8;i++){
printf("%d ",a[i]);
s2+=a[i];
}
printf("\n");
printf("%d\n",s2-s1);
return 0;
}
结果不对。。。以后心情好再改。。。