快排(尾递归的优化+随机数的优化+插入排序的优化)

本文介绍了一个使用C语言实现的快速排序算法,包括基本的快速排序过程、随机选择分区元素的方法以及插入排序用于小数组优化。代码从文件中读取整数数据并进行排序,展示了完整的排序流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

#define DataNum 20

void printfError();
void QuickSort( int a[], int s, int f );
int Partition( int a[], int s, int f );
void swap( int* a, int* b );
void InsertRank( int a[], int s, int f );
int RandPartition( int a[], int s, int f );

int main ( void ) {
    FILE *fp = fopen("data.txt", "r");
    if( !fp ) {
        printfError();
    }
    int i = 0;
    int a[DataNum];

    for( i = 0; i < DataNum; i++ ) {
        fscanf(fp, "%d", &a[i]);
    }

    QuickSort( a, 0, DataNum-1 );

    for( i = 0; i < DataNum; i++ ) {
        printf("%d ", a[i]);
    }
    return 0;
}
void printfError( ) {
    printf("Space Error\n");
    exit( 0 );
}
void QuickSort( int a[], int s, int f ) {

    if( f - s <= 4 ) {
        InsertRank( a, s, f );
        return;
    }
    else {
        int m = 0;
        while( f - s >= 5 ) {
            m = RandPartition( a, s, f );
            QuickSort( a, s, m-1 );
            s++;
        }
    }
}
int Partition( int a[], int s, int f ) {
    int x = a[f];
    int i = s-1;
    int j = s;

    for( j = s; j <= f-1; j++ ) {
        if( a[j] < x ) {
            i++;
            swap( &a[i], &a[j] );
        }
    }
    i = i+1;
    swap( &a[i], &a[f] );
    return i;
}
void swap( int* a, int* b ) {
    int c = *b;
    *b = *a;
    *a = c;
}
void InsertRank( int a[], int s, int f ) {
    int i = 0, j = 0;
    int key = 0;

    for( j = s+1; j <= f; j++ ) {
        i = j-1;
        key = a[j];

        while( i >= s && key < a[i] ) {
            a[i+1] = a[i];
            i--;
        }
        i++;
        a[i] = key;
    }
}
int RandPartition( int a[], int s, int f ) {
    int tmp = rand()%( f-s ) + s;
    swap( &a[tmp], &a[f] );
    return Partition( a, s, f );
}
待会再发一篇,欠三篇。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值