標籤:style class blog code http tar
前言:此代碼設計的比較簡潔,可能不太容易理解,插入排序就是每一步都將一個待排資料按其大小插入到已經排序的資料中的適當位置,直到全部插入完畢。 一:
二:代碼
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace InsertSort{ public partial class Frm_Main : Form { public Frm_Main() { InitializeComponent(); } private int[] G_int_value;//定義數組欄位 private Random G_Random = new Random();//建立隨機數對象 private void btn_sort_Click(object sender, EventArgs e) { if (G_int_value != null) { for (int i = 0; i < G_int_value.Length; ++i)//逐一查看數組中的元素 { int temp = G_int_value[i];//定義一個int變數,並使用獲得的數組元素值賦值 int j = i; while ((j > 0) && (G_int_value[j - 1] > temp))//判斷數組中的元素是否大於獲得的值 { G_int_value[j] = G_int_value[j - 1];//如果是,則將後一個元素的值提前 --j; } G_int_value[j] = temp;//最後將int變數儲存的值賦值給最後一個元素 } txt_str2.Clear();//清空控制項內字串 foreach (int i in G_int_value)//遍曆字串集合 { txt_str2.Text += i.ToString() + ", ";//向控制項內添加字串 } } else { MessageBox.Show("首先應當產生數組,然後再進行排序。", "提示!"); } } private void btn_Generate_Click(object sender, EventArgs e) { G_int_value = new int[G_Random.Next(10, 20)];//產生隨機長度數組 for (int i = 0; i < G_int_value.Length; i++)//遍曆數組 { G_int_value[i] = G_Random.Next(0, 100);//為數組賦隨機數值 } txt_str.Clear();//清空控制項內字串 foreach (int i in G_int_value)//遍曆字串集合 { txt_str.Text += i.ToString() + ", ";//向控制項內添加字串 } } }}