美文网首页数据结构
2020-03-06查找数组中两个相差最小的两个数的差(快速排序

2020-03-06查找数组中两个相差最小的两个数的差(快速排序

作者: 喵喵不吃鱼哦 | 来源:发表于2020-03-06 17:01 被阅读0次
#include <iostream>
#include <math.h>

using namespace std;
void quickSort(int *a,int start,int End);
int result(int arr[],int len);
int main()
{
    int a[] = {45,8,2,4,9,32,56,41,56,32,54,27,55,62};
    cout<<"排序之前元素:\n";
    for(int i = 0;i < 14; i ++ ){
        cout<<a[i]<<" ";
    }
    quickSort(a,0,13);
    cout<<"排序之后元素:\n";
    for(int i = 0;i < 14; i ++ ){
        cout<<a[i]<<" ";
    }
    cout<<"\n"<<result(a,13);

    return 0;
}

void quickSort(int arr[],int low, int high){//降序
    if(high<=low)return;
    int i = low,j = high+1;
    int key = arr[low];
    while(true){
        while(arr[++i]>key){
            if(i == high)
                break;
        }
        while(arr[--j]<key){
            if(j == low)
                break;
        }
        if(i>=j)break;
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    cout<<"交换"<<arr[i]<<" - "<<arr[j]<<"\n";
    }
        key = arr[j];
        arr[j] = arr[low];
        arr[low] = key;
        cout<<"交换中枢"<<"j="<<j<<"\n";
        quickSort(arr,low,j-1);
        quickSort(arr,j+1,high);
}
int result(int arr[],int len){
    int result =  fabs(arr[0]-arr[1]);
    for(int i= 1;i<len-1;i++){
        if(fabs(arr[i]-arr[i+1])<result){
            result = arr[i]-arr[i+1];
        }
    }
    return result;
}









相关文章

网友评论

    本文标题:2020-03-06查找数组中两个相差最小的两个数的差(快速排序

    本文链接:https://www.haomeiwen.com/subject/girwrhtx.html