微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C语言数据结构插入排序

#include <stdio.h>
#include <stdbool.h>

#define MAX 7

int intArray[MAX] = {4,6,3,2,1,9,7};

void printline(int count) {
   int i;

   for(i = 0;i < count-1;i++) {
      printf(=);
   }

   printf(=\n);
}

void display() {
   int i;
   printf([);

   // navigate through all items 
   for(i = 0;i < MAX;i++) {
      printf(%d ,intArray[i]);
   }

   printf(]\n);
}

void insertionSort() {

   int valuetoInsert;
   int holePosition;
   int i;

   // loop through all numbers 
   for(i = 1; i < MAX; i++) { 

      // select a value to be inserted. 
      valuetoInsert = intArray[i];

      // select the hole position where number is to be inserted 
      holePosition = i;

      // check if prevIoUs no. is larger than value to be inserted 
      while (holePosition > 0 && intArray[holePosition-1] > valuetoInsert) {
         intArray[holePosition] = intArray[holePosition-1];
         holePosition--;
         printf( item moved : %d\n , intArray[holePosition]);
      }

      if(holePosition != i) {
         printf( item inserted : %d, at position : %d\n , valuetoInsert,holePosition);
         // insert the number at hole position 
         intArray[holePosition] = valuetoInsert;
      }

      printf(Iteration %d#:,i);
      display();

   }  
}

void main() {
   printf(Input Array: );
   display();
   printline(50);
   insertionSort();
   printf(Output Array: );
   display();
   printline(50);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐