当前位置:编程学习 > C/C++ >>

选择排序Linux下c 实现

       选择排序,将待排序序列分为两个序列:已排序序列和未排序序列。每次从未排序序列中,选择一个最小的元素,存放在到已排序序列的最后,直到所有元素排序完毕。关键代码如下:

        1、选择排序头文件:selectSort.h


[cpp]
#ifndef SELECTSORT_H  
#define SELECTSORT_H  
extern void selectSort(int *pArr, const int length); 
#endif 

#ifndef SELECTSORT_H
#define SELECTSORT_H www.zzzyk.com
extern void selectSort(int *pArr, const int length);
#endif
          2、选择排序源文件:selectSort.c


[cpp]
#include "selectSort.h"  
void selectSort(int *pArr, const int length) 

        int i,j,min,tmp; 
        for(i=0; i<length-1; i++) 
        { 
                min =i; 
                for(j=i+1; j<length; j++) 
                { 
                        if(*(pArr+min)>*(pArr+j)) 
                        { 
                                min=j; 
                        } 
                } 
                if(min!=i) 
                { 
                        tmp=*(pArr+i); 
                        *(pArr+i)=*(pArr+min); 
                        *(pArr+min)=tmp; 
                } 
        } 

#include "selectSort.h"
void selectSort(int *pArr, const int length)
{
        int i,j,min,tmp;
        for(i=0; i<length-1; i++)
        {
                min =i;
                for(j=i+1; j<length; j++)
                {
                        if(*(pArr+min)>*(pArr+j))
                        {
                                min=j;
                        }
                }
                if(min!=i)
                {
                        tmp=*(pArr+i);
                        *(pArr+i)=*(pArr+min);
                        *(pArr+min)=tmp;
                }
        }
}
           3、main头文件:main.h


[cpp]
#ifndef MAIN_H  
#define MAIN_H  
#include<stdio.h>  
#include "selectSort.h"  
int main(void); 
void showArr(const int *pArr, const int length); 
void initRandomArr(int *pArr, const int length); 
#endif 

#ifndef MAIN_H
#define MAIN_H
#include<stdio.h>
#include "selectSort.h"
int main(void);
void showArr(const int *pArr, const int length);
void initRandomArr(int *pArr, const int length);
#endif
             4、main源文件:main.c


[cpp]
#include "main.h"  
 
int main(void) 

        printf("Input array length:\n"); 
        int length; 
        scanf("%d", &length); 
        if(length<0) 
        { 
                printf("Array length must be larger 0\n"); 
                return 1; 
        } 
        int arr[length]; 
        initRandomArr(arr, length); 
        printf("Get random array :\n"); 
        showArr(arr, length); 
        selectSort(arr, length); 
        printf("select sort result:\n"); 
        showArr(arr, length); 
        return 0; 

void showArr(const int *pArr, const int length) 

        int i; 
        for(i=0; i<length; i++) 
        { 
            &n

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,