我有一个程序,我必须在其中使用 Visual Studio 2010 将选择排序更改为 C++ 程序中的插入排序。以下代码是我显示选择排序的内容:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
int data[] = {5,6,7,1,2,4,7,8,9,11,12,13,0,7,8,5,3,2,6,8};
if (button1->Text == "Start")
{
panel1->Visible = true;
button1->Text = "Sort";
messageLabel->Text="Unsorted Array";
DrawArray(data, 20);
}
else
{
if(ascButton->Checked )
{
selectionSort(data,20,1);
messageLabel->Text="Sorted Array - Ascending";
}
else
{
selectionSort(data,20,2);
messageLabel->Text="Sorted Array - Descending";
}
DrawArray(data, 20);
}
}
private: System::Void selectionSort(int array[], int n,int ascending)
{
int temp,index; // temporary variable used for swapping and index
int i, j;
for (i = 0; i < n-1; i++)
{
index = i;
for (j = i+1; j < n; j++)
{
if(ascending==1)
{
if (array[j] < array[index])
{
index = j;
}
}
else
{
if (array[j] > array[index])
{
index = j;
}
}
}
if (index != i)
{
temp = array[i];
array[i] = array[index];
array[index] = temp;
}
} // end for
} // end method selectionSort
我实施了以下更改,程序运行没有任何错误,但数据看起来不像正在排序。以下是更新后的代码:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
int data[] = {5,6,7,1,2,4,7,8,9,11,12,13,0,7,8,5,3,2,6,8};
if (button1->Text == "Start")
{
panel1->Visible = true;
button1->Text = "Sort";
messageLabel->Text="Unsorted Array";
DrawArray(data, 20);
}
else
{
if(ascButton->Checked )
{
insertionSort(data,20,1);
messageLabel->Text="Sorted Array - Ascending";
}
else
{
insertionSort(data,20,2);
messageLabel->Text="Sorted Array - Descending";
}
DrawArray(data, 20);
}
}
private: System::Void insertionSort(int array[], int n,int ascending)
{
int data[]= {5,6,7,1,2,4,7,8,9,11,12,13,0,7,8,5,3,2,6,8};
int vacant; // Position of last vacated element
int temp; // Temporary copy of unsorted value
int i;
for (i=0; i < n-1; i++)
{
temp = data[i+1]; // Copy first unsorted value
for (vacant = i+1;
((vacant > 0) && (data[vacant-1] > temp));
vacant--)
{
data[vacant] = data[vacant-1]; // Shift data up
} // End inner loop
data[vacant] = temp; // Insert value into vacated element
} // End outer loop
}