## Big O(n^2) Ascending Sort

1 like • Nov 18, 2022
C++

## More C++ Posts

```#include <iostream>using namespace std;
main{	cout << "No tabbing. That's very sad :(\n";	cout << "No in-editor highlighting either :(((\n";	cout << "Descriptions might be niice too.";}```
```#include <iostream>using namespace std;
/* Function: get_coeffParameters: double& coeff, int pos passed from bb_4acReturn: type is void so no return, but does ask for user to input data that establishes what a b and c are.*/void get_coeff(double& coeff, int pos) {  char position;  if(pos == 1) {    position = 'a';  } else if(pos == 2) {   //a simple system to determine what coefficient the program is asking for.    position = 'b';  } else {    position = 'c';  }  cout << "Enter the co-efficient" << position << ":"; //prompt to input coeff  cin >> coeff; //input coeff}
/* Function: bb_4acParameters: no parameters passed from main, but 3 params established in function, double a, b, c.Return: b * b - 4 * a * c*/double bb_4ac() {  double a, b, c; //coefficients of a quadratic equation  get_coeff(a, 1); // call function 1st time  get_coeff(b, 2); // call function 2nd time  get_coeff(c, 3); // call function 3rd time  return b * b - 4 * a * c; //return b * b - 4 * a * c}
int main() {  cout << "Function to calculate the discriminant of the equation. . . " << endl;  double determinate = bb_4ac(); //assign double determinate to bb_4ac function  cout << "The discriminant for given values is: " << determinate << endl;  //output the determinate!}```
```//Leif Messinger//Finds all sets of 5 5 letter words that don't have duplicate letters in either themselves or each other.//First it reads the words in and puts them in groups of their bitmasks//After that, we recurse on each group. Before doing that, we remove the group from the set of other groups to check it against.#include <cstdio> //getchar, printf#include <cassert> //assert#include <vector>#include <set>#include <algorithm> //std::copy_if#include <iterator> //std::back_inserter
#define CHECK_FOR_CRLF true#define MIN_WORDS 5#define MAX_WORDS 5#define WORD_TOO_LONG(len) (len != 5)
const unsigned int charToBitmask(const char bruh){	assert(bruh >= 'a' && bruh <= 'z');	return (1 << (bruh - 'a'));}
unsigned int bitmask = 0;	unsigned int wordLength = 0;	bool duplicateLetters = false;	for(char c = getchar(); c >= 0; c = getchar()){		if(CHECK_FOR_CRLF && c == '\r'){			continue;		}		if(c == '\n'){			if(!(WORD_TOO_LONG(wordLength) || duplicateLetters)) bitmasks.insert(bitmask);			bitmask = 0;			wordLength = 0;			duplicateLetters = false;			continue;		}		if((bitmask & charToBitmask(c)) != 0) duplicateLetters = true;		bitmask |= charToBitmask(c);		++wordLength;	}
//Just to be clear, when I mean "word", I mean a group of words with the same letters.void recurse(std::vector<unsigned int>& oldBitmasks, std::vector<unsigned int> history, const unsigned int currentBitmask){	//If there's not enough words left	if(oldBitmasks.size() + (-(history.size())) + (-MIN_WORDS) <= 0){		//If there's enough words		if(history.size() >= MIN_WORDS){			//Print the list			printBitmasks(history);		}		return;	//To make it faster, we can stop it after 5 words too	}else if(history.size() >= MAX_WORDS){		//Print the list		printBitmasks(history);		return;	}
while(newBitmasks.size() > 0){		//I know this modifies 'oldBitmasks' too. It's intentional.		//This makes it so that the word is never involved in any of the child serches or any of the later searches in this while loop.		const unsigned int word = newBitmasks.back(); newBitmasks.pop_back();
std::vector<unsigned int> newHistory = history;		newHistory.push_back(word);
return 0;}```
```#include <iostream>#include <vector>#include <utility>#include <algorithm>#include <chrono>using namespace std;
#include <stdio.h>#include <Windows.h>
int nScreenWidth = 120;			// Console Screen Size X (columns)int nScreenHeight = 40;			// Console Screen Size Y (rows)int nMapWidth = 16;				// World Dimensionsint nMapHeight = 16;
float fPlayerX = 14.7f;			// Player Start Positionfloat fPlayerY = 5.09f;float fPlayerA = 0.0f;			// Player Start Rotationfloat fFOV = 3.14159f / 4.0f;	// Field of Viewfloat fDepth = 16.0f;			// Maximum rendering distancefloat fSpeed = 5.0f;			// Walking Speed
int main(){	// Create Screen Buffer	wchar_t *screen = new wchar_t[nScreenWidth*nScreenHeight];	HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);	SetConsoleActiveScreenBuffer(hConsole);	DWORD dwBytesWritten = 0;
// Create Map of world space # = wall block, . = space	wstring map;	map += L"#########.......";	map += L"#...............";	map += L"#.......########";	map += L"#..............#";	map += L"#......##......#";	map += L"#......##......#";	map += L"#..............#";	map += L"###............#";	map += L"##.............#";	map += L"#......####..###";	map += L"#......#.......#";	map += L"#......#.......#";	map += L"#..............#";	map += L"#......#########";	map += L"#..............#";	map += L"################";
auto tp1 = chrono::system_clock::now();	auto tp2 = chrono::system_clock::now();		while (1)	{		// We'll need time differential per frame to calculate modification		// to movement speeds, to ensure consistant movement, as ray-tracing		// is non-deterministic		tp2 = chrono::system_clock::now();		chrono::duration<float> elapsedTime = tp2 - tp1;		tp1 = tp2;		float fElapsedTime = elapsedTime.count();

// Handle CCW Rotation		if (GetAsyncKeyState((unsigned short)'A') & 0x8000)			fPlayerA -= (fSpeed * 0.75f) * fElapsedTime;
// Handle CW Rotation		if (GetAsyncKeyState((unsigned short)'D') & 0x8000)			fPlayerA += (fSpeed * 0.75f) * fElapsedTime;				// Handle Forwards movement & collision		if (GetAsyncKeyState((unsigned short)'W') & 0x8000)		{			fPlayerX += sinf(fPlayerA) * fSpeed * fElapsedTime;;			fPlayerY += cosf(fPlayerA) * fSpeed * fElapsedTime;;			if (map.c_str()[(int)fPlayerX * nMapWidth + (int)fPlayerY] == '#')			{				fPlayerX -= sinf(fPlayerA) * fSpeed * fElapsedTime;;				fPlayerY -= cosf(fPlayerA) * fSpeed * fElapsedTime;;			}					}
// Handle backwards movement & collision		if (GetAsyncKeyState((unsigned short)'S') & 0x8000)		{			fPlayerX -= sinf(fPlayerA) * fSpeed * fElapsedTime;;			fPlayerY -= cosf(fPlayerA) * fSpeed * fElapsedTime;;			if (map.c_str()[(int)fPlayerX * nMapWidth + (int)fPlayerY] == '#')			{				fPlayerX += sinf(fPlayerA) * fSpeed * fElapsedTime;;				fPlayerY += cosf(fPlayerA) * fSpeed * fElapsedTime;;			}		}
for (int x = 0; x < nScreenWidth; x++)		{			// For each column, calculate the projected ray angle into world space			float fRayAngle = (fPlayerA - fFOV/2.0f) + ((float)x / (float)nScreenWidth) * fFOV;
// Find distance to wall			float fStepSize = 0.1f;		  // Increment size for ray casting, decrease to increase													float fDistanceToWall = 0.0f; //                                      resolution
bool bHitWall = false;		// Set when ray hits wall block			bool bBoundary = false;		// Set when ray hits boundary between two wall blocks
float fEyeX = sinf(fRayAngle); // Unit vector for ray in player space			float fEyeY = cosf(fRayAngle);
// Incrementally cast ray from player, along ray angle, testing for 			// intersection with a block			while (!bHitWall && fDistanceToWall < fDepth)			{				fDistanceToWall += fStepSize;				int nTestX = (int)(fPlayerX + fEyeX * fDistanceToWall);				int nTestY = (int)(fPlayerY + fEyeY * fDistanceToWall);								// Test if ray is out of bounds				if (nTestX < 0 || nTestX >= nMapWidth || nTestY < 0 || nTestY >= nMapHeight)				{					bHitWall = true;			// Just set distance to maximum depth					fDistanceToWall = fDepth;				}				else				{					// Ray is inbounds so test to see if the ray cell is a wall block					if (map.c_str()[nTestX * nMapWidth + nTestY] == '#')					{						// Ray has hit wall						bHitWall = true;
// To highlight tile boundaries, cast a ray from each corner						// of the tile, to the player. The more coincident this ray						// is to the rendering ray, the closer we are to a tile 						// boundary, which we'll shade to add detail to the walls						vector<pair<float, float>> p;
// Test each corner of hit tile, storing the distance from						// the player, and the calculated dot product of the two rays						for (int tx = 0; tx < 2; tx++)							for (int ty = 0; ty < 2; ty++)							{								// Angle of corner to eye								float vy = (float)nTestY + ty - fPlayerY;								float vx = (float)nTestX + tx - fPlayerX;								float d = sqrt(vx*vx + vy*vy); 								float dot = (fEyeX * vx / d) + (fEyeY * vy / d);								p.push_back(make_pair(d, dot));							}
// Sort Pairs from closest to farthest						sort(p.begin(), p.end(), [](const pair<float, float> &left, const pair<float, float> &right) {return left.first < right.first; });												// First two/three are closest (we will never see all four)						float fBound = 0.01;						if (acos(p.at(0).second) < fBound) bBoundary = true;						if (acos(p.at(1).second) < fBound) bBoundary = true;						if (acos(p.at(2).second) < fBound) bBoundary = true;					}				}			}					// Calculate distance to ceiling and floor			int nCeiling = (float)(nScreenHeight/2.0) - nScreenHeight / ((float)fDistanceToWall);			int nFloor = nScreenHeight - nCeiling;
// Shader walls based on distance			short nShade = ' ';			if (fDistanceToWall <= fDepth / 4.0f)			nShade = 0x2588;	// Very close				else if (fDistanceToWall < fDepth / 3.0f)		nShade = 0x2593;			else if (fDistanceToWall < fDepth / 2.0f)		nShade = 0x2592;			else if (fDistanceToWall < fDepth)				nShade = 0x2591;			else											nShade = ' ';		// Too far away
if (bBoundary)		nShade = ' '; // Black it out						for (int y = 0; y < nScreenHeight; y++)			{				// Each Row				if(y <= nCeiling)					screen[y*nScreenWidth + x] = ' ';				else if(y > nCeiling && y <= nFloor)					screen[y*nScreenWidth + x] = nShade;				else // Floor				{									// Shade floor based on distance					float b = 1.0f - (((float)y -nScreenHeight/2.0f) / ((float)nScreenHeight / 2.0f));					if (b < 0.25)		nShade = '#';					else if (b < 0.5)	nShade = 'x';					else if (b < 0.75)	nShade = '.';					else if (b < 0.9)	nShade = '-';					else				nShade = ' ';					screen[y*nScreenWidth + x] = nShade;				}			}		}
// Display Stats		swprintf_s(screen, 40, L"X=%3.2f, Y=%3.2f, A=%3.2f FPS=%3.2f ", fPlayerX, fPlayerY, fPlayerA, 1.0f/fElapsedTime);
// Display Map		for (int nx = 0; nx < nMapWidth; nx++)			for (int ny = 0; ny < nMapWidth; ny++)			{				screen[(ny+1)*nScreenWidth + nx] = map[ny * nMapWidth + nx];			}		screen[((int)fPlayerX+1) * nScreenWidth + (int)fPlayerY] = 'P';
// Display Frame		screen[nScreenWidth * nScreenHeight - 1] = '\0';		WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeight, { 0,0 }, &dwBytesWritten);	}
return 0;}```
```#include <iostream>using namespace std;
int main() {  const int ROW_SIZE = 2;  const int COLUMN_SIZE = 5;              //establish all variables  int matrix[ROW_SIZE][COLUMN_SIZE];  int minVal;
for (int i = 0; i < ROW_SIZE; ++i)    // for loop to ask user to enter data.  {    for (int h = 0; h < COLUMN_SIZE; ++h) {      cout << "Enter data for row #" << i + 1 << " and column #" << h + 1 << ": ";      cin >> matrix[i][h];    }  }  cout << "You entered: " << endl;  for (int i = 0; i < ROW_SIZE; ++i) //for statements to output the array neatly  {    for (int h = 0; h < COLUMN_SIZE; ++h) {      cout << matrix[i][h] << "\t";    }    cout << endl;  }
cout << "Minimum for each row is: {";  for (int i = 0; i < ROW_SIZE; i++) //for statements to find the minimum in each row  {    minVal = matrix[i];
for (int h = 0; h < COLUMN_SIZE; h++) {      if (matrix[i][h] < minVal) // if matrix[i][h] < minVal -> minVal = matrix[i][h];      {        minVal = matrix[i][h];      }    }    cout << minVal << ", ";  }  cout << "}" << endl;
cout << "Minimum for each column is: {";  for (int i = 0; i < COLUMN_SIZE; i++) //for statements to find the minimum in each column  {    minVal = matrix[i];    for (int h = 0; h < ROW_SIZE; h++) {      if (matrix[h][i] < minVal) //replaces minVal with array index for that column that is lowest      {        minVal = matrix[h][i];      }    }    cout << minVal << ", ";  }  cout << "}" << endl;
return 0;}```
```#include <string>#include <iostream>#include "PlaylistNode.h"using namespace std;
PlaylistNode::PlaylistNode() {   uniqueID = "none";   songName = "none";   artistName = "none";   songLength = 0;   nextNodePtr = 0;}
PlaylistNode::PlaylistNode(string uniqueID_, string songName_, string artistName_, int songLength_) {   uniqueID = uniqueID_;   songName = songName_;   artistName = artistName_;   songLength = songLength_;   nextNodePtr = 0;}
void PlaylistNode::InsertAfter(PlaylistNode* ptr) {   this->SetNext(ptr->GetNext());   ptr->SetNext(this);}
void PlaylistNode::SetNext(PlaylistNode* ptr) {   nextNodePtr = ptr;}
string PlaylistNode::GetID() {   return uniqueID;}
string PlaylistNode::GetSongName() {   return songName;}
string PlaylistNode::GetArtistName() {   return artistName;}
int PlaylistNode::GetSongLength() {   return songLength;}
PlaylistNode* PlaylistNode::GetNext() {   return nextNodePtr;}
void PlaylistNode::PrintPlaylistNode() {   cout << "Unique ID: " << uniqueID << endl;   cout << "Song Name: " << songName << endl;   cout << "Artist Name: " << artistName << endl;   cout << "Song Length (in seconds): " << songLength << endl;}
Playlist::Playlist() {   head = tail = 0;}
void Playlist::AddSong(string id, string songname, string artistname, int length) {   PlaylistNode* n = new PlaylistNode(id, songname, artistname, length);   if (head == 0) {      head = tail = n;   }   else {      n->InsertAfter(tail);      tail = n;   }}
bool Playlist::RemoveSong(string id) {   if (head == NULL) {      cout << "Playlist is empty" << endl;      return false;   }      PlaylistNode* curr = head;   PlaylistNode* prev = NULL;   while (curr != NULL) {      if (curr->GetID() == id) {         break;      }      prev = curr;      curr = curr->GetNext();   }      if (curr == NULL) {      cout << "\"" << curr->GetSongName() << "\" is not found" << endl;      return false;   }   else {      if (prev != NULL) {         prev ->SetNext(curr->GetNext());      }      else {         head = curr->GetNext();      }      if (tail == curr) {         tail = prev;      }      cout << "\"" << curr->GetSongName() << "\" removed." << endl;      delete curr;      return true;   }}
bool Playlist::ChangePosition(int oldPos, int newPos) {   if (head == NULL) {      cout << "Playlist is empty" << endl;      return false;   }      PlaylistNode* prev = NULL;   PlaylistNode* curr = head;      int pos;   if (head == NULL || head == tail) {      return false;   }      for (pos = 1; curr != NULL && pos < oldPos; pos++) {      prev = curr;      curr = curr->GetNext();   }   if (curr != NULL) {      string currentSong = curr->GetSongName();            if (prev == NULL) {         head = curr->GetNext();      }      else {         prev->SetNext(curr->GetNext());      }      if (curr == tail) {         tail = prev;      }            PlaylistNode* curr1 = curr;      prev = NULL;      curr = head;      for (pos = 1; curr != NULL && pos < newPos; pos++) {         prev = curr;         curr = curr->GetNext();      }      if (prev == NULL) {         curr1->SetNext(head);         head = curr1;      }      else {         curr1->InsertAfter(prev);      }      if (curr == NULL) {         tail = curr1;      }      cout << "\"" << currentSong << "\" moved to position " << newPos << endl;      return true;   }   else {      cout << "Song's current position is invalid" << endl;      return false;   }}
void Playlist::SongsByArtist(string artist) {   if (head == NULL) {      cout << "Playlist is empty" << endl;   }   else {      PlaylistNode* curr = head;      int i = 1;      while (curr != NULL) {         if (curr->GetArtistName() == artist) {            cout << endl << i << "." << endl;            curr->PrintPlaylistNode();         }         curr = curr->GetNext();         i++;      }   }}
int Playlist::TotalTime() {   int total = 0;   PlaylistNode* curr = head;      while (curr != NULL) {      total += curr->GetSongLength();      curr = curr->GetNext();   }   return total;}
void Playlist::PrintList() {   if (head == NULL) {      cout << "Playlist is empty" << endl;   }   else {      PlaylistNode* curr = head;      int i = 1;      while (curr != NULL) {         cout << endl << i++ << "." << endl;         curr->PrintPlaylistNode();         curr = curr->GetNext();      }   }}```