//■ヒープソート // コマンドボタンを2個,ListBoxを2個配置する 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 HeapSort { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private int[] data = new int[20]; private void button1_Click(object sender, EventArgs e) { listBox1.Items.Clear(); Random R = new Random(); for (int i = 0; i < data.Length; i++) listBox1.Items.Add(R.Next(1, 100).ToString()); } private void dspData() { listBox2.Items.Clear(); for (int i = 0; i < data.Length; i++) listBox2.Items.Add(data[i].ToString()); } private void setData() { for (int i = 0; i < data.Length; i++) { listBox1.SelectedIndex = i; data[i] = int.Parse(listBox1.SelectedItem.ToString()); } listBox1.SelectedIndex = -1; } private void ヒープ化(ref int[] a, int 左, int 右) { int AA = a[左], 子, 親; for (親 = 左; 親 < (右 + 1) / 2; 親 = 子) { int 左の子 = 親 * 2 + 1, 右の子 = 左の子 + 1; 子 = (右の子 <= 右 && a[右の子] > a[左の子]) ? 右の子 : 左の子; if (AA >= a[子]) break; a[親] = a[子]; } a[親] = AA; } private void swap(ref int X, ref int Y) { int D = X; X = Y; Y = D; } private void ヒープソート() { int i; for (i = (data.Length - 1) / 2; i >= 0; i--) ヒープ化(ref data, i, data.Length - 1); for (i = data.Length - 1; i > 0; i--) { swap(ref data[0], ref data[i]); ヒープ化(ref data, 0, i - 1); } } private void button2_Click(object sender, EventArgs e) { setData(); ヒープソート(); dspData(); } } }