Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Основная книга по С++й.doc
Скачиваний:
16
Добавлен:
28.10.2018
Размер:
2.07 Mб
Скачать

InsertSort(d, max); // Сортируем массив b методом вставок

end = clock();

float f2 = (float)(end-begin); // Измеряем время, занятое сортировкой методом вставок

printf ("Сортировка массива из %i элементов методом вставок заняла \t%.0f msec.\r\n", MAX, f2);

// Просмотр отсортированных данных?

printf("\r\n\r\n\r\nВы хотите просмотреть отсортированные данные? (y/n)");

short Key = 0;

while (Key = _getch()) // Ожидание нажатия на кнопку

{

if (Key == 'n' || Key == 'N' || Key == 27) // если нажата кнопк N или Esc, то

return 0; // выход

else if (Key == 'y' || Key == 'Y') // если y, то

break; // то продолжаем

}

printf("\r\n\r\n\r\n\r\n");

printf(" N.\tБез сортировки\tN.\tМетод «пузырька»\tN.\tМетод выбора\tN.\tМетод вставки\r\n");

printf("\r\n");

for (int i = 0; i < MAX; i++)

printf("%3i.\t%5i\t%3i.\t%5i\t%3i.\t%5i\t%3i.\t%5i\r\n",

i+1, a[i], i+1, b[i], i+1, c[i], i+1, d[i]); // Печать содержимого массивов

printf("\r\nНажмите любую кнопку для продолжения\r\n");

Key = 0;

while (!Key) Key = _getch(); // Ожидание нажатия на кнопку

}

Результат выполнения программы

Введите количество элементов : 10000

Сортировка массива из 10000 элементов методом "пузырька" заняла 1139 msec.

Сортировка массива из 10000 элементов методом выбора заняла 175 msec.

Сортировка массива из 10000 элементов методом вставок заняла 113 msec.

Вы хотите просмотреть отсортированные данные? (y/n)

N. Без сортировки N. Метод «пузырька» N. Метод выбора N. Метод вставки

1. 30410 1. 1072 1. 1072 1. 1072

2. 7475 2. 1219 2. 1219 2. 1219

3. 13312 3. 1405 3. 1405 3. 1405

4. 30386 4. 1911 4. 1911 4. 1911

5. 27070 5. 3080 5. 3080 5. 3080

6. 11743 6. 6686 6. 6686 6. 6686

7. 23967 7. 6981 7. 6981 7. 6981

8. 7718 8. 7229 8. 7229 8. 7229

9. 24750 9. 7457 9. 7457 9. 7457

10. 29293 10. 7475 10. 7475 10. 7475

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Пример 8. Процедуры для организации и работы с односвязными списками.

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

#include <conio.h>

#include <iostream>

#include <windows.h>

using namespace std;

class Node

{

public:

Int number;

Node* next;

};

Int main()

{

Node* head = NULL;

Node* lastPtr = NULL;

short action = -1;

while (1)

{

printf("1. Добавить Элемент\n");

printf("2. Просмотр Списка\n");

printf("3. Поиск Элемента\n");

printf("4. Удалить Элемент\n");

printf("5. Удалить Элемент По Выбору\n");

printf("0. Выход\n\n");

printf("Ваш Выбор: ");

cin>>action;

if (action == 0)

{

system("CLS");

break;

}

if (action == 1)

{

system("CLS");

Node* ptr = new Node;

int numb = -1;

printf("Введите Число: ");

cin>>numb;

ptr->number = numb;

ptr->next = NULL;

if (head == 0)

{

head = ptr;

lastPtr = ptr;

system("CLS");

continue;

}

lastPtr->next = ptr;

lastPtr = ptr;

system("CLS");

continue;

}

if (action == 2)

{

Node* ptr = NULL;

system("CLS");

if (head == NULL)

{

printf("\t!!! СПИСОК ПУСТ !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

printf("* * * * * СПИСОК * * * * *\n\n");

ptr = head;

while (1)

{

cout<<ptr->number<<" ";

if (ptr->next == 0)

break;

ptr = ptr->next;

}

cout<<"\n\n";

system("PAUSE");

system("CLS");

continue;

}

if (action == 3)

{

Node* ptr = NULL;

int key = -1;

system("CLS");

if (head == NULL)

{

printf("\t!!! СПИСОК ПУСТ !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

printf("Введите Элемент Для Поиска: ");

cin>>key;

ptr = head;

while (1)

{

if (key == ptr->number)

{

printf("\n\t!!! ЭЛЕМЕНТ НАЙДЕН !!!\n");

break;

}

if (ptr->next == NULL)

{

printf("\n\t!!! ЭЛЕМЕНТ НЕ НАЙДЕН !!!\n");

break;

}

ptr = ptr->next;

}

system("PAUSE");

system("CLS");

continue;

}

if (action == 4)

{

system("CLS");

Node* ptrDelete = NULL;

if (head == NULL)

{

printf("\t!!! СПИСОК ПУСТ !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

if (head->next == NULL)

{

head = NULL;

delete head;

continue;

}

ptrDelete = head;

head = ptrDelete->next;

delete ptrDelete;

continue;

}

if (action == 5)

{

system("CLS");

Node* ptrPrev = NULL;

Node* ptrDelete = NULL;

int key = -1;

if (head == NULL)

{

printf("\t!!! СПИСОК ПУСТ !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

printf("Введите Элемент Для Удаления: ");

cin>>key;

ptrDelete = head;

if (ptrDelete->number == key)

{

head = ptrDelete->next;

delete ptrDelete;

system("CLS");

continue;

}

while (1)

{

if (key == ptrDelete->number)

{

ptrPrev->next = ptrDelete->next;

delete ptrDelete;

break;

}

if (ptrDelete->next == 0)

{

printf("\n\t!!! ЭЛЕМЕНТ НЕ НАЙДЕН !!!\n");

system("PAUSE");

break;

}

ptrPrev = ptrDelete;

ptrDelete = ptrDelete->next;

}

system("CLS");

continue;

}

if (action > 5)

{

system("CLS");

printf("\t!!! НЕВЕРНЫЙ ВЫБОР. ПОВТОРИТЕ ВВОД !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

}

}

Результат выполнения программы (меню программы)

1. Добавить Элемент

2. Просмотр Списка

3. Поиск Элемента

4. Удалить Элемент

5. Удалить Элемент По Выбору

0. Выход

Ваш Выбор:

Пример 9. Процедуры для организации и работы с двусвязными списками.

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

#include <conio.h>

#include <iostream>

#include <windows.h>

using namespace std;

class Node

{

public:

int number;

Node* next;

Node* last;

};

void main()

{

short action = -1;

Node* head = NULL;

Node* tail = NULL;

Node* ptrLast = NULL;

while (1)

{

puts("1. Добавить Элемент\n");

puts("2. Просмотр Списка слева направо\n");

puts("3. Просмотр Списка направа слево\n");

puts("4. Удалить головной элемент\n");

puts("5. Удалить последний элемент\n");

puts("6. Поиск элемента\n");

puts("0. Выход\n\n");

puts("Ваш выбор: ");

cin>>action;

if (action == 0)

{

system("CLS");

break;

}

if (action == 1)

{

system("CLS");

int numb = -1;

puts("Введите число: ");

cin>>numb;

Node* ptr = new Node;

ptr->number = numb;

ptr->next = NULL;

tail = ptr;

if (head == NULL)

{

head = ptr;

ptrLast = ptr;

ptr->last = NULL;

system("CLS");

continue;

}

ptr->last = ptrLast;

ptrLast->next = ptr;

ptrLast = ptr;

system("CLS");

continue;

}

if (action == 2)

{

system("CLS");

Node* ptr = NULL;

if (head == NULL)

{

puts("\t!!! Список пуст !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

puts("* * * * * Список: слева направо * * * * *\n\n");

ptr = head;

while (1)

{

cout<<ptr->number<<" ";

if (ptr->next == 0)

break;

ptr = ptr->next;

}

cout<<"\n\n";

system("PAUSE");

system("CLS");

continue;

}

if (action == 3)

{

system("CLS");

Node* ptr = NULL;

if (head == NULL)

{

puts("\t!!! Список пуст !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

puts("* * * * * Список: справа налево * * * * *\n\n");

ptr = tail;

while (1)

{

cout<<ptr->number<<" ";

if (ptr->last == 0)

break;

ptr = ptr->last;

}

cout<<"\n\n";

system("PAUSE");

system("CLS");

continue;

}

if (action == 4)

{

system("CLS");

Node* ptrDelete = NULL;

if (head == NULL)

{

puts("\t!!! Список пуст !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

if (head->next == NULL)

{

head = NULL;

tail = NULL;

delete head;

continue;

}

ptrDelete = head;

head = ptrDelete->next;

head->last = NULL;

delete ptrDelete;

continue;

}

if (action == 5)

{

system("CLS");

Node* ptrDelete = NULL;

if (tail == NULL)

{

puts("\t!!! Список пуст !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

if (tail->last == NULL)

{

head = NULL;

tail = NULL;

delete tail;

continue;

}

ptrDelete = tail;

tail = ptrDelete->last;

tail->next = NULL;

ptrLast = tail;

delete ptrDelete;

continue;

}

if (action == 6)

{

system("CLS");

Node* ptr = NULL;

int key = -1;

if (head == NULL)

{

puts("\t!!! Список пуст !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

puts("Введите искомый элемент: ");

cin>>key;

ptr = head;

while (1)

{

if (key == ptr->number)

{

puts("\n\t!!! Элемент найден !!!\n");

break;

}

if (ptr->next == NULL)

{

puts("\n\t!!! Элемент не найден !!!\n");

break;

}

ptr = ptr->next;

}

system("PAUSE");

system("CLS");

continue;

}

if (action > 6)

{

system("CLS");

puts("\t!!! Неверный выбор. Повторите ввод !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

}

}

Результат выполнения программы (меню программы)

1. Добавить Элемент

2. Просмотр Списка слева направо

3. Просмотр Списка направа слево

4. Удалить головной элемент

5. Удалить последний элемент

6. Поиск элемента

0. Выход

Ваш выбор:

Пример 10. Процедуры для организации очередей и работы с ними.

class Node

{

public:

int number;

Node* last;

Node* next;

};

int main()

{

Node* head = NULL;

Node* tail = NULL;

Node* ptrLast = NULL;

short action = -1;

while(1)

{

printf("1. Добавить Элемент\n");

printf("2. Просмотр Очереди\n");

printf("3. Удалить Элемент\n");

printf("4. Поиск Элемента\n");

printf("0. Выход\n\n");

printf("Ваш Выбор: ");

cin>>action;

if (action == 0)

{

system("CLS");

break;

}

if (action == 1)

{

system("CLS");

int numb = -1;

printf("Введите Число: ");

cin>>numb;

Node* ptr = new Node;

ptr->number = numb;

ptr->next = NULL;

tail = ptr;

if (head == NULL)

{

head = ptr;

ptrLast = ptr;

ptr->last = NULL;

system("CLS");

continue;

}

ptr->last = ptrLast;

ptrLast->next = ptr;

ptrLast = ptr;

system("CLS");

continue;

}

if (action == 2)

{

system("CLS");

Node* ptr = NULL;

if (head == NULL)

{

printf("\t!!! ОЧЕРЕДЬ ПУСТА !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

printf("* * * * * ОЧЕРЕДЬ * * * * *\n\n");

ptr = tail;

while (1)

{

cout<<ptr->number<<" ";

if (ptr->last == 0)

break;

ptr = ptr->last;

}

cout<<"\n\n";

system("PAUSE");

system("CLS");

continue;

}

if (action == 3)

{

system("CLS");

Node* ptrDelete = NULL;

if (head == NULL)

{

printf("\t!!! ОЧЕРЕДЬ ПУСТА !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

if (head->next == NULL)

{

head = NULL;

tail = NULL;

delete tail;

continue;

}

ptrDelete = head;

head = ptrDelete->next;

head->last = NULL;

delete ptrDelete;

continue;

}

if (action == 4)

{

system("CLS");

Node* ptr = NULL;

int key = -1;

if (head == NULL)

{

printf("\t!!! СПИСОК ПУСТ !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

printf("Введите Элемент Для Поиска: ");

cin>>key;

ptr = head;

while (1)

{

if (key == ptr->number)

{

printf("\n\t!!! ЭЛЕМЕНТ НАЙДЕН !!!\n");

break;

}

if (ptr->next == NULL)

{

printf("\n\t!!! ЭЛЕМЕНТ НЕ НАЙДЕН !!!\n");

break;

}

ptr = ptr->next;

}

system("PAUSE");

system("CLS");

continue;

}

if (action > 4)

{

system("CLS");

printf("\t!!! НЕВЕРНЫЙ ВЫБОР. ПОВТОРИТЕ ВВОД !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

}

}

Результат выполнения программы (меню программы)

1. Добавить Элемент

2. Просмотр Очереди

3. Удалить Элемент

4. Поиск Элемента

0. Выход

Ваш выбор:

Пример 11. Процедуры для организации и работы со стеками.

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

#include <conio.h>

#include <iostream>

#include <windows.h>

using namespace std;

class Node

{

public:

int number;

Node* last;

};

int main()

{

Node* ptrLast = NULL;

Node* top = NULL;

short action = -1;

while (1)

{

printf("1. Затолкнуть В Стек\n");

printf("2. Вытолкнуть Из Стека\n");

printf("3. Вершина Стека\n");

printf("4. Содержимое Стека\n");

printf("0. Выход\n\n");

printf("Ваш Выбор: ");

cin>>action;

if (action == 0)

{

system("CLS");

break;

}

if (action == 1)

{

system("CLS");

int numb = -1;

printf("Введите Число: ");

cin>>numb;

Node* ptr = new Node;

ptr->number = numb;

if (top == NULL)

{

ptr->last = NULL;

top = ptr;

ptrLast = ptr;

system("CLS");

continue;

}

top = ptr;

ptr->last = ptrLast;

ptrLast = ptr;

system("CLS");

continue;

}

if (action == 2)

{

system("CLS");

Node* ptrDelete = NULL;

if (top == NULL)

{

printf("\t!!! СТЕК ПУСТ !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

ptrDelete = top;

if (ptrDelete->last == NULL)

{

top = NULL;

delete ptrDelete;

system("CLS");

continue;

}

top = ptrDelete->last;

ptrLast = top;

delete ptrDelete;

continue;

}

if (action == 3)

{

system("CLS");

if (top == NULL)

{

printf("\t!!! СТЕК ПУСТ !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

printf("Вершина Стека: ");

cout<<top->number<<"\n\n";

system("PAUSE");

system("CLS");

continue;

}

if (action == 4)

{

system("CLS");

Node* ptr = NULL;

if (top == NULL)

{

printf("\t!!! СТЕК ПУСТ !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

printf("* * * * * СОДЕРЖИМОЕ СТЕКА * * * * *\n\n");

ptr = top;

while (1)

{

cout<<ptr->number<<endl;

if (ptr->last == NULL)

{

system("PAUSE");

system("CLS");

break;

}

ptr = ptr->last;

}

}

if (action > 4)

{

system("CLS");

printf("\t!!! НЕВЕРНЫЙ ВЫБОР. ПОВТОРИТЕ ВВОД !!!\n\n");

system("PAUSE");

system("CLS");

continue;

}

}

}

Результат выполнения программы (меню программы)

1. Затолкнуть В Стек

2. Вытолкнуть Из Стека

3. Вершина Стека

4. Содержимое Стека

0. Выход

Ваш выбор:

Пример 12. Алгоритм решения задачи «Ханойская башня».

Ханойская башня является одной из популярных головоломок XIX века. Даны три стержня, на один из которых нанизаны восемь колец, причем кольца отличаются размером и лежат меньшее на большем. Задача состоит в том, чтобы перенести пирамиду из восьми колец за наименьшее число ходов. За один раз разрешается переносить только одно кольцо, причём нельзя класть большее кольцо на меньшее.

Эту известную игру придумал французский математик Эдуард Люка, в 1883 году её продавали как забавную игрушку. Первоначально она называлась «Профессор Клаус (Claus) из Коллеж Ли-Су-Стьян (Li-Sou-Stian)», но вскоре обнаружилось, что таинственный профессор из несуществующего колледжа  не более чем анаграмма фамилии изобретателя игры  профессора Люка (Lucas) из коллежа Сен-Луи (Saint Louis).