3.4 Метод сортування бульбашкою
Алгоритм метод бульбашки - найбільш простий метод сортування масиву. через
своєї простоти цей метод не дуже ефективний і вимагає процесорного часу
більше, ніж інші методи. Однак для сортування невеликих масивів
використання методу бульбашки прийнятно. Припустимо, що масив сортується в
порядку зростання, тоді метод бульбашки використовує цикл за значеннями масиву,
переміщаючи поступово найбільше значення в кінець масиву (подібно до того, як в
воді спливає на поверхню пляшечку).
Сортування методом бульбашки займає 61,3 секунд.
ВЫВОДЫ
Написание курсовой работы позволило закрепить теоретические знания языка С++. Были приобретены основные навыки работы со средой программирования Microsoft Visual Studio 2008 а конкретней с СRL Windows Forms. В курсовой работе не только показаны все способы расставить 8 ферзей на шахматной доске ,и посчитано сколько таких расстановок существует ,но и реализован простой ,но в тоже время удобный интерфейс , в котором пользователь может в понятном виде просмотреть все расстановки.
ПЕРЕЧЕНЬ ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
1. Страуструп, Б. Язык программирования С++. Часть 1 [Текст] / Б. Страуструп; перевод с англ. – К.: ДиаСофт, 1993. – 264 с.
2. Страуструп, Б. Язык программирования С++. Часть 2 [Текст] / Б. Страуструп; перевод с англ. – К.: ДиаСофт, 1993. – 296 с.
3. Соловьева Ф.И. Введение в теорию кодирования: Учебное пособие/ Новосибирск. гос. ун-т. Новосибирск, 2006. с.127.
4. Павловская Т.А.: «C/C++. Программирование на языке высокого уровня – СПб.: Питер, 2004. – 461 с.;
5. Пархомов, Б. С/С++ и МS Visual C++ 2008 для начинающих , 2009. 609 с.
6. Новиков Ф.А. Дискретная математика для программистов, 2006. 600 с.
Приложение а
Файл «Form1.h» :
#pragma once
#include <string>
#include <fstream>
#include <vector>
#include "Chess.h"
const char endStr[] = {13,10,0} ; //конец строки для textBox1
namespace KYYYRSAAAVVVV {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
this->currentElement=0;
this->readFromClass(0);
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
protected:
private: System::Windows::Forms::RichTextBox^ richTextBox1;
private: System::Windows::Forms::Button^ button3;
private: System::Windows::Forms::Button^ button4;
private: System::Windows::Forms::Label^ label1;
private: int currentElement;//номер элемента, который на экране сейчас.
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox());
this->button3 = (gcnew System::Windows::Forms::Button());
this->button4 = (gcnew System::Windows::Forms::Button());
this->label1 = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(0, 244);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 0;
this->button1->Text = L"выход";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// richTextBox1
//
this->richTextBox1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->richTextBox1->Location = System::Drawing::Point(12, 12);
this->richTextBox1->Name = L"richTextBox1";
this->richTextBox1->ScrollBars = System::Windows::Forms::RichTextBoxScrollBars::Horizontal;
this->richTextBox1->Size = System::Drawing::Size(292, 220);
this->richTextBox1->TabIndex = 2;
this->richTextBox1->Text = L"";
this->richTextBox1->TextChanged += gcnew System::EventHandler(this, &Form1::richTextBox1_TextChanged);
//
// button3
//
this->button3->Location = System::Drawing::Point(268, 241);
this->button3->Name = L"button3";
this->button3->Size = System::Drawing::Size(36, 26);
this->button3->TabIndex = 4;
this->button3->Text = L">>";
this->button3->UseVisualStyleBackColor = true;
this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
//
// button4
//
this->button4->Location = System::Drawing::Point(87, 238);
this->button4->Name = L"button4";
this->button4->Size = System::Drawing::Size(33, 29);
this->button4->TabIndex = 5;
this->button4->Text = L"<<";
this->button4->UseVisualStyleBackColor = true;
this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(178, 248);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(37, 13);
this->label1->TabIndex = 6;
this->label1->Text = L"0 из 0";
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(316, 279);
this->Controls->Add(this->label1);
this->Controls->Add(this->button4);
this->Controls->Add(this->button3);
this->Controls->Add(this->richTextBox1);
this->Controls->Add(this->button1);
this->Name = L"Form1";
this->Text = L"Шахматы ! Курсовая Корженко";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { Form1::Close();
}
private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void printPreviewDialog1_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void openFileDialog1_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) {
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void файлToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void выходToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { Form1::Close();
}
private: System::Void richTextBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void readFromClass(int a) {
this->label1->Text=a.ToString();
this->label1->Text+=" из ";
this->label1->Text+=(Chess::n-1).ToString();
this->richTextBox1->Text = Chess::getOut(a);
}
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
if(this->currentElement>0){
this->currentElement--;
this->readFromClass(this->currentElement);
}
}
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
if(this->currentElement<Chess::n-1){
this->currentElement++;
this->readFromClass(this->currentElement);
}
}
};
}
Файл «Chess.h» :
#pragma once
ref class Chess
{
public:
static char ** mas;//массив
static int N=8;//размер доски
static int stringSize=1000;//
static System::String^ getOut(int a);//получить из массива
static int n;//кол-во расстановок
static int currentStringToWrite=0;//
static bool Check(int K, int Y);
static char *X=new char[N];//
static void MainProc(int k);
static void Display();
static int Count=0;
Chess(void);
Chess(int);
};
Файл «Chess.cpp» :
#include "StdAfx.h"
#include "Chess.h"
//System::String^ Chess::out= gcnew String();//для массива ответов
Chess::Chess(void)
{
}
Chess::Chess(int a){
Chess::n=a;
Chess::mas=new char*[a];
for(int i=0;i<a;i++){
Chess::mas[i]=new char[Chess::stringSize];
}
Chess::MainProc(0);
}
System::String^ Chess::getOut(int a){
if(a>Chess::n) throw 99;
System::String^ out = gcnew System::String("");//создает пустую строку
for(int i=0;i<Chess::stringSize && mas[a][i]!='\0';i++){
if(mas[a][i]=='Q')
out+=" Q ";
if(mas[a][i]=='\n')
out+="\n";
if(mas[a][i]=='*')
out+=" \x17\x17 ";
}
return out;
}
bool Chess::Check(int K, int Y)
{
int i=0;
while ((i < K) && (Y != X[i]) && (abs(K - i) != abs(Y - X[i]))) i++;
return (i == K);
}
void Chess::MainProc(int k)
{
for (int y = 0; y<Chess::N; y++)
if (Chess::Check(k, y))
{
Chess::X[k] = y;
if (k == (Chess::N - 1))
{
Chess::Display();
Chess::Count++;
Chess::n=Chess::Count;
}
Chess::MainProc(k + 1);
}
}
void Chess::Display(){
int num=0;//номер символа который сохраняем сейчас
for (int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
if(j==X[i])Chess::mas[currentStringToWrite][num]='Q';
else Chess::mas[currentStringToWrite][num]='*';
num++;
}
Chess::mas[currentStringToWrite][num]='\n';//перевод строки
num++;
}
Chess::mas[currentStringToWrite][num]='\0';//end строки
Chess::currentStringToWrite++;
}
Файл «KYYYRSAAAVVVV.cpp» :
// KYYYRSAAAVVVV.cpp : main project file.
#include "stdafx.h"
#include "Form1.h"
#include "Chess.h"
using namespace KYYYRSAAAVVVV;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Chess::Chess(100);
// Create the main window and run it
Application::Run(gcnew Form1());
return 0;
}
