Data structure algorithm learning summary - MOOC (2) Check the execution time and correctness of the sorting algorithm (from small to large)

Data Structure Algorithm Learning Summary

1. Ideas

Execution time: only need to record the time before sorting, the time after sorting, and then subtract the time required for sorting

Correctness: Loop the elements in the array, if the previous element in the array is larger than the next element, the sorting algorithm is incorrect, otherwise it is correct

Pay attention to the corner marks, if the boundary is exceeded, unpredictable errors may occur.

2. Code

SortTestHelper.h

#ifndef SORTTESTHELPER_H_
#define SORTTESTHELPER_H_

#include <iostream>
#include <ctime>
#include <cassert>
using namespace std;

namespace SortTestHelper{
	//Generate a random array of n elements, the random range of each element is [rangeL,rangeR]
	int* generateRandomArray(int n,int rangeL,int rangeR){
		assert(rangeL <= rangeR); //For program stability, if rangeL>rangeR, the program will not be executed
		int *arr = new int[n];
		srand(time(NULL));//Random seed, need to import ctime library
		for(int i = 0;i<n;i++){
			arr[i] = rand() % (rangeR - rangeL + 1) + rangeL; //You can do the math yourself
		}
		return arr;
	}


	/**
	 * Check the correctness of sorting
	 */
	template<typename T>
	bool isSorted (T arr [], int n) {
		for(int i = 0;i<n;i++){
			//Note that if i=n-2, the values ​​of arr[n-2] and arr[n-1] will actually be compared, and the array has been compared at this time
			if(i<n-1 && arr[i]>arr[i+1]){
				return false;
			}
		}
		return true;
	}


	/**
	 * The time required to test the sorting
	 */
	template<typename T>
	void testSort(string sortName,void(*sort)(T arr[],int n),T arr[],int n){
		clock_t startTime = clock();
		sort(arr,n);
		clock_t endTime = clock();
		assert (isSorted (arr, n));
		cout <<sortName<<" : "<< double(endTime - startTime) /CLOCKS_PER_SEC <<"s" << endl;
		return;
	}
}



#endif /* SORTTESTHELPER_H_ */

SelectionSort.cpp

#include <iostream>
#include "Student.h"
#include "SortTestHelper.h"
using namespace std;


/**
 * selection sort
 */
template<typename T>
void selectionSort(T arr[],int n){
	for(int i = 0;i<n;i++){
		int minIndex = i;
		for(int j = i+1;j<n;j++){
			if(arr[j] < arr[minIndex]){
				minIndex = j;
			}
		}
		swap(arr[minIndex],arr[i]);//Swap a and b
	}
}


template<typename T>
void printArray(T arr[],int n){
	for(int i = 0;i<n;i++)
		cout << arr[i] << " "; // loop to print the elements in the array
	cout << endl;
}




int main() {
	int n = 100000;
	int *arr = SortTestHelper::generateRandomArray(n,1,100);


	SortTestHelper::testSort("Selection Sort",selectionSort,arr,n);
	delete[] arr;//new way to open up array space to prevent memory leaks
	return 0;
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325747739&siteId=291194637