--------------------------------------------------------------
--------------------------------------------------------------
主要程式碼:
#include <cstdlib>
#include <ctime>
int* randomData;
int n;
void swap(int *x, int *y)
{ int temp;
temp = *x;
*x = *y;
*y = temp;
}
void SelectionSort(int* data, int n)
{ int i, j, min;
for (i=0; i<n-1; i++)
{ min = i;
for (j=i+1; j<n; j++)
if (data[j]<data[min]) min = j;
swap(&data[i], &data[min]);
}
}
int BinarySearch(int* data, int x, int n)
{ SelectionSort(data, n);
int lower=0, upper=n-1;
while (lower<=upper)
{int mid = (lower+upper)/2;
if (data[mid] == x)
return(mid);
else if (data[mid] < x)
lower = mid+1;
else
upper = mid-1;
}
return -1;
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) // Random Data
{ listBox1->Items->Clear();
n = int::Parse(textBox1->Text);
int range = int::Parse(textBox2->Text);
randomData = new int[n];
srand(time(NULL)); // srand(time_t(NULL));
for (int i=0;i<n;i++)
{ randomData[i] = rand()%range+1;
}
if (checkBox1->Checked)
{ for(int i=0;i<n;i++)
{ listBox1->Items->Add(randomData[i]);
}
}
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) // Run Selection Sort
{ listBox2->Items->Clear();
int* copyData = new int[n];
for (int i=0;i<n;i++)
{ copyData[i] = randomData[i];
}
clock_t start=clock();
SelectionSort(copyData, n);
clock_t end=clock();
double costTime = Math::Round((double)(end-start)/CLK_TCK, 6);
label2->Text=Convert::ToString(costTime);
if checkBox2->Checked)
{ for(int i=0;i<n;i++)
{ listBox2->Items->Add(copyData[i]);
}
}
}
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) // Run Binary Search
{
int result, x = int::Parse(textBox3->Text);
int* copyData = new int[n];
for (int i=0;i<n;i++)
{ copyData[i] = randomData[i];
}
clock_t start=clock();
result=BinarySearch(copyData, x, n);
clock_t end=clock();
double costTime = Math::Round((double)(end-start)/CLK_TCK, 6);
label2->Text=Convert::ToString(costTime);
if (result==-1)
label8->Text = "Not Found!";
else
label8->Text = "Found!";
}