关于排序的几种
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace datastruct
{
public struct DataType
{
public int key;
}
public partial class Form1 : Form
{
public DataType[] myMaoPao = new DataType[9];
public Form1()
{
InitializeComponent();
myMaoPao[0].key = 3;
myMaoPao[1].key = 2;
myMaoPao[2].key = 1;
myMaoPao[3].key = 6;
myMaoPao[4].key = 5;
myMaoPao[5].key = 4;
myMaoPao[6].key = 8;
myMaoPao[7].key = 9;
myMaoPao[8].key = 7;
}
//交换排序:冒泡排序属于交换排序的一种,进行n-1次的比较,两个连续的进行比较
private void MaoPaoSort(DataType[] a,int n)
{
int temp;
for(int i=1;i<n;i++)
{
for (int j = 0; j < n-i; j++)
{
if (a[j].key >a[j+1].key)
{
temp=a[j].key;
a[j].key = a[j + 1].key;
a[j + 1].key = temp;
}
}
}
}
//插入排序,顺序的把待排序的数据元素按其值的大小排到已经排序数据元素中
public void ShunXuSort(DataType[] a,int n)
{
int temp;
int i, j;
for (i = 0; i < n - 1; i++)
{
temp = a[i + 1].key;
j = i;
while (j > -1 && temp < a[j].key)
{
a[j+1]=a[j];
j--;
}
a[j + 1].key = temp;
}
}
//选择排序,从待排序的元素集合中选择最小的一个数据元素并将它与原始数据集合中的最小的交换位置
private void SelectSort(DataType[] a, int n)
{
int i, j, temp;
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[j].key < a[i].key)
{
temp = a[i].key;
a[i] = a[j];
a[j].key = temp;
}
}
}
}
private void maopao_Click(object sender, EventArgs e)
{
MaoPaoSort(myMaoPao,9);
for (int i = 0; i < myMaoPao.Length; i++)
{
this.label1.Text += myMaoPao[i].key.ToString();
}
}
private void insert_Click(object sender, EventArgs e)
{
ShunXuSort(myMaoPao, 9);
for (int i = 0; i < myMaoPao.Length; i++)
{
this.label2.Text += myMaoPao[i].key.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
SelectSort(myMaoPao, 9);
for (int i = 0; i < myMaoPao.Length; i++)
{
this.label3.Text += myMaoPao[i].key.ToString();
}
}
}
}