Skip to content

Instantly share code, notes, and snippets.

@dpappa
Last active August 29, 2015 14:01
Show Gist options
  • Save dpappa/514cb8b8f9e34839821e to your computer and use it in GitHub Desktop.
Save dpappa/514cb8b8f9e34839821e to your computer and use it in GitHub Desktop.
Insertion Sort
//main
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
#define sourcefilepath "unsorted.txt"
#define destinationfilepath "sorted.txt"
void WriteToFile(std::vector<int> myVector)
{
ofstream myFile ("sorted.txt");
cout << "________________" << endl;
cout << "Sorted" << endl;
for (int j = 0; j < myVector.size(); j++)
{
myFile << myVector[j] << '\n';
cout << myVector[j] << endl;
}
myFile.close();
return;
}
void Insertsort()
{
ifstream myFile ("unsorted.txt");
string line;
if (myFile.is_open())
{
std::vector<int> unsortedVector;
cout << "unsorted" << endl;
while (getline(myFile,line)){
unsortedVector.push_back(atoi (line.c_str()));
cout << line << '\n';
}
int item = 0; int steps = 0;
for (int i = 0; i < unsortedVector.size(); i++)
{
item = unsortedVector[i]; // store the current item temporarily
steps = i-1;
while ( steps >= 0 && (unsortedVector[steps] > item))
{
unsortedVector[steps + 1] = unsortedVector[steps];// shift each item one place to the right as I go
steps--; // move the pointer one to the left
}
unsortedVector[steps + 1]=item;
}
WriteToFile(unsortedVector);
}
myFile.close();
}
int main(int argc, char* argv[]) {
for (int i=0; i < argc -1; i++){
if (argv[1] == string("-i")) {
Insertsort();
}
else
cout << "Please enter a valid command" << '\n';
}
return 0;
}
@kodieGlosser
Copy link

//main

include

include

include

using namespace std;

define sourcefilepath "unsorted.txt"

define destinationfilepath "sorted.txt"

void Insertsort()
{
ifstream myFile ("unsorted.txt");
string line;

if (myFile.is_open())
{
    while (getline(myFile,line)){
       cout << line << '\n';
    }   
}
myFile.close();

}

int main(int argc, char* argv[]) {
for (int i=0; argc < -1; i++){

    if (argv[i] == string("-i"))
        Insertsort();

    else
        cout << "Please enter a valid command" << '\n';
}

return 0;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment