1. 程式人生 > >氣泡排序 二分查詢

氣泡排序 二分查詢

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int[] myArray = new int[] { 30,1,-9,70,25,44,67,34,88,30,23,-18};
            for(int i = 0; i < myArray.Length-1; i++)
            {
                for (int j = 0; j < myArray.Length-1-i; j++)
                {
                    if(myArray[j] > myArray[j+1])
                    {
                        int temp = myArray[j+1];
                        myArray[j+1] = myArray[j];
                        myArray[j] = temp;
                    }
                }
            }
            String str="";
            for (int i = 0; i < myArray.Length; i++)
            {
                str = str+" "+myArray[i].ToString();
            }
            label2.Text = str;
        }
    }
}

氣泡排序

二分查詢

在label中無法顯示陣列

解決方法:String str="";定義 字串str並賦初值” ”後

str = str+" "+myArray[i].ToString();str接收已排序陣列再在label中顯示。

剛開始寫二分查詢時找到分支

if (sortArray[mid] == num) labelRes.Text = "已找到";

程式陷入死迴圈

解決方法:加break;結束