Function - Sort
Function - Sort
order. After each bubble, we will print out a list to check (using printList).
#include <iostream>
#include <sstream>
using namespace std;
if (this->count == 0)
{
this->head = this->tail = pNew;
}
else
{
this->tail->next = pNew;
this->tail = pNew;
}
this->count++;
}
int size()
{
return this->count;
}
void printList()
{
stringstream ss;
ss << "[";
Node *ptr = head;
while (ptr != tail)
{
ss << ptr->data << ",";
ptr = ptr->next;
}
if (count > 0)
ss << ptr->data << "]";
else
ss << "]";
cout << ss.str() << endl;
}
public:
class Node {
private:
T data;
Node* next;
friend class SLinkedList<T>;
public:
Node() {
next = 0;
}
Node(T data) {
this->data = data;
this->next = nullptr;
}
};
void bubbleSort();
};
----------
template <class T>
void SLinkedList<T>::bubbleSort()
{
for (int i = this->count-1; i > 0; i--){
for (int j = 0; j <= i; j++){
Node* node = this->head;
for (int l = 0; l < j-1; l++) node = node->next;
if (node->data > node->next->data) {
T temp = node->data;
node->data = node->next->data;
node->next->data = temp;
}
}
this->printList();
}
}
==========
Implement static method selectionSort in class Sorting to sort an array in
ascending order. After each selection, we will print out a list to check (using
printArray).
#include <iostream>
using namespace std;
#ifndef SORTING_H
#define SORTING_H
#include <sstream>
#include <iostream>
#include <type_traits>
using namespace std;
public:
// TODO: Write your code here
static void sortSegment(T* start, T* end, int segment_idx, int
cur_segment_total);
static void ShellSort(T* start, T* end, int* num_segment_list, int num_phases);
};
#endif /* SORTING_H */
----------
// TODO: Write your code here
#ifndef SORTING_H
#define SORTING_H
#include <sstream>
#include <iostream>
#include <type_traits>
using namespace std;
template <class T>
class Sorting {
private:
static T* Partition(T* start, T* end) ;
public:
static void QuickSort(T* start, T* end) ;
};
#endif /* SORTING_H */
----------
static T* Partition(T* start, T* end) {
T pivot = *start;
int i = 0;
int j = end-start+1;
do {
// i qua phải đến khi a[i] >= pivot
do i++; while (*(start+i) < pivot);
// j qua trái đến khi a[j] <= pivot
do j--; while (*(start+j) > pivot);
T temp = *(start+i);
*(start+i) = *(start+j);
*(start+j) = temp;
} while (i<j);
T temp = *(start+i);
*(start+i) = *(start+j);
*(start+j) = temp;
temp = *(start);
*(start) = *(start+j);
*(start+j) = temp;
cout << j << ' ';
return (start+j); // Index của phần tử pivot
}
static void QuickSort(T* start, T* end) {
if (end <= start) return;
T* q = Partition(start, end);
QuickSort(start,q);
QuickSort(q+1,end);
}