最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

簡單了解C語言中直接插入排序與直接選擇排序?qū)崿F(xiàn)

 更新時(shí)間:2016年03月12日 11:26:26   作者:lixiang0522  
這篇文章主要介紹了C語言中直接插入排序與直接選擇排序?qū)崿F(xiàn),插入排序的基本操作就是將一個(gè)數(shù)據(jù)插入到已經(jīng)排好序的有序數(shù)據(jù)中,從而得到一個(gè)新的、個(gè)數(shù)加一的有序數(shù)據(jù),需要的朋友可以參考下

直接插入排序
基本思路:
1. 從a[0]開始,也就是從1個(gè)元素開始是有序的,a[1]~a[n-1]是無序的。
2. 從a[1]開始并入前面有序的數(shù)組,直到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開始通過對比找出最小的數(shù)的下標(biāo)。然后把這個(gè)下標(biāo)的值和0交換。
2. 循環(huán)把值交換到1 2 3 ... n-1。

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


相關(guān)文章

最新評論

新营市| 菏泽市| 上林县| 大余县| 永吉县| 广昌县| 察雅县| 阳泉市| 呼图壁县| 华阴市| 砀山县| 鄢陵县| 龙岩市| 禹城市| 鄄城县| 定州市| 临猗县| 柯坪县| 绥宁县| 京山县| 泰安市| 五莲县| 托里县| 大冶市| 徐州市| 迁安市| 龙岩市| 萨嘎县| 鄂州市| 策勒县| 威远县| 前郭尔| 贡觉县| 中超| 从江县| 东源县| 甘泉县| 呼和浩特市| 江津市| 扶风县| 武城县|