插入排序(c++实现)
生活随笔
收集整理的這篇文章主要介紹了
插入排序(c++实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
github博客傳送門
csdn博客傳送門
插入排序原理:
#include<iostream> using namespace std;//插入排序 void InsertionSort(int a[], int size) {int i; //有序區間的最后一個元素的位置,i+1就是無序區間最左邊元素的位置for(i = 0; i < size-1; ++i){int tmp = a[i + 1]; //tmp是待插入到有序區間的元素,即無序區間最左邊的元素int j = i;while(j >= 0 && tmp < a[j]){ //尋找插入的位置 a[j + 1] = a[j]; //比tmp大的元素都往后移動 --j;}a[j + 1] = tmp;} }//輸出二維數組,rows是行數 void PrintArray(int a[][5], int rows) {for(int i = 0; i < rows; ++i){for(int j = 0; j < 5; ++j)cout << a[i][j] << " ";cout << endl;} } //主函數 int main(){int b[5] = {50, 30, 20, 10, 40};int a2d[3][5] = {{5, 3, 2, 1, 4},{10, 20, 50, 40, 30},{100, 120, 50, 140, 30}};InsertionSort(b, 5);for(int i = 0; i < 5; ++i)cout << b[i] << " ";cout << endl;for(int i = 0; i < 3; ++i) //將 a2d每一行均排序 InsertionSort(a2d[i], 5);PrintArray(a2d, 3);return 0; }輸出:
轉載于:https://www.cnblogs.com/Mrzhang3389/p/10127398.html
總結
以上是生活随笔為你收集整理的插入排序(c++实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据量庞大的分页穿梭框实现
- 下一篇: c# 协变与抗变