加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

简单了解C语言中直接插入排序与直接选择排序实现

发布时间:2020-12-16 05:33:34 所属栏目:百科 来源:网络整理
导读:直接插入排序 基本思路: 1. 从a[0]开始,也就是从1个元素开始是有序的,a[1]~a[n-1]是无序的。 2. 从a[1]开始并入前面有序的数组,直到n-1。 #include stdio.h #define N 5 void insertsort(int a[],int n); void swap(int *x,int *y); void insertsort(int

直接插入排序
基本思路:
1. 从a[0]开始,也就是从1个元素开始是有序的,a[1]~a[n-1]是无序的。
2. 从a[1]开始并入前面有序的数组,直到n-1。

#include <stdio.h> 
#define N 5 
 
void insertsort(int a[],int n); 
void swap(int *x,int *y); 
 
void insertsort(int a[],int n){ 
  int i,j; 
  for(i=1; i<n; i++){ 
    for(j=i; j>0 && a[j]<a[j-1]; j--){ 
      swap(&a[j],&a[j-1]); 
    }   
  } 
} 
 
void swap(int *x,int *y){ 
  int i = *x; 
  *x = *y; 
  *y = i; 
} 
 
int main(void){ 
  int a[N] = {2,5,3,1,8}; 
  insertsort(a,N); 
  int i; 
  for(i=0; i<N; i++) 
    printf("%d ",a[i]); 
  return 0; 
} 


直接选择排序

基本思路:
1. 从1开始通过对比找出最小的数的下标。然后把这个下标的值和0交换。
2. 循环把值交换到1 2 3 ... n-1。

#include <stdio.h> 
#define N 5 
 
void selectsort(int a[],int *y); 
 
void selectsort(int a[],j; 
  for(i=0; i<n; i++){ 
    int min = i; 
    for(j=i+1; j<n; j++){ 
      if(a[j] < a[min]){ 
        min = j; 
      } 
    } 
    swap(&a[i],&a[min]); 
  } 
} 
 
void swap(int *x,8}; 
  selectsort(a,a[i]); 
  return 0; 
} 


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读