Radix sort c++ implementation - c++

I am having trouble trying to implement a radix sort. This is an assignment, and my professor is less than willing to even point me in the right direction. I have been staring at this code for a long time. Can someone explain to me why my pointers are not working? I did some inspection, and saw that my pointer is not even pointing to the next pointer, and I am very confused as to why. I am not asking for anyone to do my assignment, just some direction.
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define COLUMN 10
using namespace std;
struct List{
int data;
List *p;
};
struct node{
int len = 0;
List *p = NULL;
};
void printList(int list[], int len){
for (int i = 0;i<len;i++){
cout <<list[i] << " ";
}
cout << "\n";
}
void deleteList(node columns[], int len){
for (int j =0; j<COLUMN;j++){
List *curr;
List *prev;
curr = columns[j].p;
for (int i = 0; i<len;i++){
prev = curr;
curr = curr->p;
delete prev;
}
delete curr;
}
}
void overrideArray(node columns[], int a[], int len){
int k = 0; List *curr;
for (int i = 0;i<COLUMN,k<len;i++){
int len = columns[i].len;
cout << len << " length"<< endl;
curr =columns[i].p;
for (int j = 0;j<len;j++){
cout << "plue\n";
if (len == 0) continue;
cout << k <<" plue2\n";
a[k]=curr->data;
cout << "plue3\n";
cout << a[k] << " value";
curr = curr->p;
k++;
}
}
printList(a,len);
}
int main(){
srand(time(NULL));
int length = 10, m,n,i;
node *columns = new node[COLUMN];
List * curr;
int *a = new int [length];
for (int i = 0;i<length;i++){
a[i] = 2;
}
printList(a,length);
m = 10; n = 1; i =0;
while(columns[0].len!=length){
int loc = (a[i]%m)/n;
//cout << loc << endl;
curr = columns[loc].p;
while(curr != NULL){
//cout << "here" << endl;
curr = curr->p;
//cout << curr->data << endl;
}
curr = new List;
cout << curr->p << endl;
curr->data = a[i];
cout << curr->p << endl;
columns[loc].len++;
i++;
if (i == length-1){
overrideArray(columns,a,length);
cout << "here5\n";
deleteList(columns,length);
cout << "here6\n";
i = 0;
m *= 10;
n*=10;
}
}
overrideArray(columns,a,length);
printList(a,length);
return 0;
}

Related

Experiencing a segmentation fault inconsistently with my implementation of a hash table with linear probing

Trying to implement a hash table with linear probing for a project but I am running into a few issues, where I think one of them is the main culprit.
For starters, after compiling the code, if I were to run the program 10 times in a row, I would experience a segmentation fault: 11 around 2/3 of the time.
When the code does actually run, it seems to "mostly" work. indicies 9500-10000 are perfect with all slots filled. But when continuing down(9000-9500), more than 10 NULL spaces are seen and there are some slots filled with bogus values, ie. value > 100,000.
I am using a dataset of 10,000 integers from a csv file all with values < 100,000. I was going to try to debug this using GDB and core however my computer isn't too pleased with my installing it at the moment.
#ifndef HASHLINEAR_HPP
#define HASHLINEAR_HPP
struct node{
int key;
};
class HashLinear{
struct node** table;
int tableSize;
int numCollisions = 0;
public:
HashLinear(int bsize);
void insert(int key);
unsigned int hashFunction(int key);
int search(int key);
int getCollisions();
void printTable();
};
#endif
#include "hashlinear.hpp"
#include <iostream>
using namespace std;
HashLinear::HashLinear(int bsize){
this->tableSize = bsize;
table = new node*[tableSize];
for(int i = 0; i < tableSize; i++){
table[i] = NULL;
}
}
int HashLinear::getCollisions(){
return numCollisions;
}
unsigned int HashLinear::hashFunction(int key){
return key % tableSize;
}
void HashLinear::insert(int key){
node* newNode = new node;
newNode->key = key;
int index = hashFunction(key);
while(table[index] != NULL && table[index]->key != key){
numCollisions++;
index = (index + 1) % tableSize;
}
table[index] = newNode;
}
int HashLinear::search(int key){
int value = hashFunction(key);
int num = 0;
while(table[value] != NULL){
num = 0;
if(num++ > tableSize){
break;
}
if(table[value]->key == key){
return value;
}
value++;
value %= tableSize;
}
return -1;
}
void HashLinear::printTable(){
for(int i = 0; i < tableSize; i++){
cout << i << " || ";
if(table[i] == NULL){
cout << "NULL" << endl;
}
else{
cout << table[i]->key << endl;
}
}
}
#include "hashlinear.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <time.h>
#include <stdlib.h>
#include <chrono>
using namespace std;
int main(){
//******Read in data******//
int testData[10000];
float insertTime[100];
float searchTime[100];
int index = 0;
string line, temp, word;
ifstream inputFile;
inputFile.open("dataSetA-updatedhashlinear.csv");
if(inputFile.fail()){
cout << "Could not open data." << endl;
return -1;
}
else{
while(inputFile >> temp){
getline(inputFile, temp);
stringstream inStream(temp);
while(getline(inStream, word, ',')){
testData[index] = stoi(word);
index++;
}
}
inputFile.close();
}
//******Read in data******//
//cout << "Printing random data in range of 0 ~ 10: " << testData[rand() % 10 + 0] << endl;
//******Insert/Search data in Linked List******//
HashLinear table(10009);
int hashIndex = 0;
int insertTimeIndex = 0;
int searchTimeIndex = 0;
int num = 0;
int upperIndex = 99;
while(hashIndex < 10009){
//Block for 100 insertions
auto insertionStart = chrono::steady_clock::now();//Insert time start
for(int i = hashIndex; i < upperIndex; i++){ //Keep track of current index as well as an upper index to control amount of inserts
table.insert(testData[i]);
hashIndex++;
}
auto insertionEnd = chrono::steady_clock::now();
insertTime[insertTimeIndex] = chrono::duration_cast<chrono::microseconds>(insertionEnd - insertionStart).count() / 100.0;//Insert time end
insertTimeIndex++;
//Block for 100 insertions
//Block for 100 searches
num = 0;
auto searchStart = chrono::steady_clock::now();//Search time start
while(num < 100){ //Do 100 random searches from 0 index to upperindex
srand((unsigned)time(0));
int searchNode = table.search(testData[rand() % upperIndex + 0]);
num++;
}
auto searchEnd = chrono::steady_clock::now();
searchTime[searchTimeIndex] = chrono::duration_cast<chrono::microseconds>(searchEnd - searchStart).count() / 100.0;//Search time end
searchTimeIndex++;
//Block for 100 searches
upperIndex += 100;
}
//******Insert/Search data in Linked List******//
//******TESTING******//
table.printTable();
cout << "Search time: " << searchTime[20] << endl;
cout << "Insert time: " << insertTime[20] << endl;
cout << "Collisons: " << table.getCollisions() << endl;
int testIndex = table.search(34262);
cout << "Index of 34262: " << testIndex << endl;
//******TESTING******//
}
So after some more debugging I figured out I am just slow. I was iterating 100 times past the end of the testData array creating bogus values and making the hash table not fill correctly.

in graph data structure using linklist values of nodes are changed

this is a graph data structure using link list.
so i got stuck at the values of node are changed.
im putting output first and then code.
why this is happnning.
(this is output in that im printing node values and they changed why
enter no of edges=
4
enter no of nodes
4
#0#1#2#3
#1#2#0#3
enter connection
)
//here is the code
#include <iostream>
using namespace std;
struct graph
{
int nn;
int ne;
struct node *a;
};
struct node
{
int x;
node *next;
};
void makegraph(graph *&g)
{
cout << "enter no of edges=" << endl;
cin >> g->ne;
cout << "enter no of nodes" << endl;
cin >> g->nn;
g->a = new node[g->nn];
node *q;
node *ih = g->a;
for (int i = 0; i < g->nn; i++)
{
ih->x = i;
cout << "#" << ih->x;
ih->next = NULL;
ih = ih + i;
}
cout << endl;
int ii = 0;
ih = g->a;
while (ii < 4)
{
cout << "#" << (ih + ii)->x;
ii++;
}
cout << endl;
int t, y;
node *temp = NULL;
for (int i = 0; i < g->ne; i++)
{
cout << "enter connection" << endl;
****output is of till here****
cin >> t >> y;
q = new node;
q->x = y;
q->next = NULL;
g->a = g->a + t;
temp = g->a;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = q;
g->a = g->a - t;
}
g->a = ih;
}
int main()
{
graph *g = new graph;
makegraph(g);
}

read access violation when I tried to implement Depth First Search algorithm in c++

this is my DFS function. I don't know why visited[start_vertex] doesn't work although I allocated the visited array in the main function!
typedef Node** PtP;
void DFS(PtP list, int start_vertex, bool* visited)
{
cout << "the crash under this line";
if (visited[start_vertex])
{
cout << "ignore";
}
visited[start_vertex] = true;
Node* adj = list[start_vertex]; // linked list list[0]
// after this line start_vertex will be adjacency vertex of start vertex
while (adj != NULL)
{
DFS(list, adj->data, visited);
adj = adj->next;
}
}
this is my main function I created an bool array and allocated its by four element and plug in the DFS function
int main()
{
PtP list;
list = new Node * [4];
for (int i = 0; i < 4; i++)
{
list[i] = new Node[4];
list[i] = NULL;
}
for (int i = 0; i < 4; i++)
{
cout << "enter number of vertices adjacency with " << i << ": ";
int temp;
cin >> temp;
addEdge2(list, i, temp);
}
for (int i = 0; i < 4; i++)
{
cout << "list[" << i << "]: ";
traverse(list[i]);
}
bool* visited = new bool[4];
for (int i = 0; i < 4; i++)
{
visited = false;
}
DFS(list, 0, visited);
for (int i = 0; i < 4; i++)
{
cout << "visisted: " << visited[i] << " ";
}
for (int i = 0; i < 4; i++)
{
delete [] list[i];
}
delete [] list;
return 0;
}
and this is my entire program just for test DFS method:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
typedef Node* Ptr;
typedef Node** PtP;
void addFront(Ptr& First, int x)
{
Ptr p;
p = new Node;
p->data = x;
p->next = First;
First = p;
}
void addEdge(PtP &list, int v1, int v2)
{
addFront(list[v1], v2);
addFront(list[v2], v1);
}
void addEdge2(PtP& list, int v, int num_of_adj_vtex)
{
cout << "enter vertices adjacency with " << v << ": ";
int temp;
for (int i = 0; i < num_of_adj_vtex; i++)
{
cin >> temp;
addFront(list[v], temp);
}
}
void traverse(Node* first)
{
Node* p = first;
while (p != NULL)
{
cout << p->data<<" ";
p = p->next;
}
cout << "\n";
}
void DFS(PtP list, int start_vertex, bool* visited)
{
if (visited[start_vertex])
{
cout << "vertex: " << start_vertex << " visited ";
}
visited[start_vertex] = true;
// linked list list[0] after this line start_vertex will be adjaceny vertex of start vertex
Node* adj = list[start_vertex];
while (adj != NULL)
{
DFS(list, adj->data, visited);
adj = adj->next;
}
}
int main()
{
PtP list; //type def node ** ptp
list = new Node * [4];
for (int i = 0; i < 4; i++)
{
list[i] = NULL;
}
for (int i = 0; i < 4; i++)
{
cout << "enter number of vertices adjacency with " << i << ": ";
int temp;
cin >> temp;
addEdge2(list, i, temp);
}
for (int i = 0; i < 4; i++)
{
cout << "list[" << i << "]: ";
traverse(list[i]);
}
bool* visited = new bool[4];
for (int i = 0; i < 4; i++)
{
visited[i] = false;
}
DFS(list, 0, visited);
for (int i = 0; i < 4; i++)
{
cout << "visisted: " << i << " "<< visited[i] << " ";
}
delete [] list;
return 0;
}
Ok, from what I can see, the problem seems to be user input related. The method:
void addEdge2(PtP& list, int v, int num_of_adj_vtex)
{
cout << "enter vertices adjacency with " << v << ": ";
int temp;
for (int i = 0; i < num_of_adj_vtex; i++)
{
cin >> temp;
addFront(list[v], temp); //Here if temp > 3 your later code will fail.
}
}
Requests user input and stores it at the front of the list...whatever is the value of temp, and puts it into the data field.
Later on when you do the DFS method you call the same method recursively:
DFS(list, adj->data, visited);
adj = adj->next;
This depends on what adj->data has stored, from the addEdge2 function. Since you have set the boolean array to a length of 4, that adj->data must be pointing to any value > 3 which would throw the error you mentioned because it is trying to access unallocated memory.
It seems like the code is not wrong, exactly, even though you could probably set some safeguards like making sure the user enters a value from 0 to 3.

Bubble Sort By Moving Nodes in Linked List (C++)

I am doing bubble sort on linked list by comparing values in nodes and then moving nodes but there is a problem in my function. When i run my code it creates nodes fine but when bubblesort() function runs it throws an exception and it says "p2 was nullptr". I don't know what is wrong in my code and any help would be appreciated.
Here is my code:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Node {
public:
int number;
Node* next;
};
class LinkedList {
Node* head;
Node* tail;
public:
LinkedList() {
head = NULL;
tail = NULL;
}
void createnode(int num) {
Node* temp = new Node;
temp->number = num;
temp->next = NULL;
if (head == NULL) {
head = temp;
tail = temp;
}
else {
tail->next = temp;
tail = temp;
}
}
void bubblesort(int size) {
Node* temp;
int i, j, swapped;
for (i = 0; i <= size; i++){
temp = head;
swapped = 0;
for (j = 0; j < size - i - 1; j++){
Node* p1 = temp;
Node* p2 = p1->next;
if (p1->number > p2->number){
Node* temp1 = p2->next;
p2->next = p1;
p1->next = temp1;
temp = p2;
swapped = 1;
}
temp = temp->next;
}
if (swapped == 0)
break;
}
}
void displaynodes() {
Node* temp;
temp = head;
while (temp != NULL) {
cout << temp->number << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
LinkedList l;
int size, num;
cout << "How many Numbers Do You Want to Store: ";
cin >> size;
for (int i = 0; i < size; i++) {
cout << "Enter Number " << i+1 << ": ";
cin >> num;
l.createnode(num);
}
system("CLS");
cout << "Data Of Nodes Before Bubble Sort: " << endl;
l.displaynodes();
l.bubblesort(size);
cout << "Data Of Nodes After Bubble Sort: " << endl;
l.displaynodes();
system("pause");
}
You have many bad coding practice like using namespace std;, bad naming style and using Null instead of nullptr.
However the error was in the sorting snippet. You are trying to swapping the nodes but you can't do that without using the node previous to the current node or using doubly linked list. So in the following code, I swapped the numbers not the nodes.
void bubblesort(int size) {
int i, j, swapped = 1;
for (i = 0; swapped && i < size; i++){
swapped = 0;
Node* temp = head;
for (j = 0; j < size - i - 1; j++){
if (temp->number > temp -> next ->number){
int tempNumber = temp -> number;
temp -> number = temp -> next -> number;
temp -> next -> number = tempNumber;
swapped = 1;
}
temp = temp->next;
}
}
}

Pointer issue while implementing suffix tree in c++

I was trying to implement suffix tree using c++ by looking at some examples online. I am running into pointer issue and I am not able to fix it. Any help is greatly appreciated.
/*
* Implement suffix array to print the maximum suffix substring in a string
* Algorithm:
* Build a suffix tree and find the lowest node with multiple children
*
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <ctype.h>
using namespace std;
struct node{
char ch;
node* next[26];
int treeHeight;
int childCount;
int end = 0;
};
void insertSuffixIntoTree(node*& root, string suffix){
if (suffix.size() == 0){
return;
}
char c = suffix[0];
int index = tolower(c) - 'a';
if (root->next[index] == NULL){
root->next[index] = new node();
for (int k = 0; k < 26; k++){
root->next[index]->next[k] = NULL;
}
root->next[index]->ch = tolower(c);
if (suffix.size() == 1){
root->next[index]->end = 1;
}
}
suffix.erase(suffix.begin());
insertSuffixIntoTree(root->next[index], suffix);
}
void buildSuffixTree(node* root, string str){
if (root == NULL) cout << "CRAP" << endl;
for (int i = str.size() - 1; i >= 0; i--){
string suffix = str.substr(i);
cout << "suffix is " << suffix << endl;
insertSuffixIntoTree(root, suffix);
}
}
void printSuffixTree(node* root, string str){
if (root->end){
cout << str << endl;
return;
}
for (int i = 0; i<26; i++){
while (root->next[i]){
str += root->ch;
return printSuffixTree(root->next[i],str);
}
}
}
int main() {
string str;
node* suffixRoot = new node();
suffixRoot->ch = ' ';
for (int i = 0; i < 26; i++){
suffixRoot->next[i] = NULL;
}
cout << "enter the string" << endl;
cin >> str;
buildSuffixTree(suffixRoot, str);
//string result = findMaxSuffix(suffixRoot,str);
//cout<<"result is "<<result<<endl;
string result = "";
printSuffixTree(suffixRoot,result);
getchar();
return 0;
}
The error is happening at insertIntoSuffixTree method inside buildSuffixTree method. My understanding is I am loosing my pointer address I started with. Any idea on how to get around this issue?
Sorry for any inconvenience. I fixed the code as seen below:
/*
* Implement suffix array to print the maximum suffix substring in a string
* Algorithm:
* Build a suffix tree and find the lowest node with multiple children
*
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <ctype.h>
using namespace std;
struct node{
char ch;
node* next[26];
int treeHeight;
int childCount;
int end = 0;
};
void insertSuffixIntoTree(node* root, string suffix){
if (suffix.size() == 0){
return;
}
char c = suffix[0];
int index = tolower(c) - 'a';
if (root->next[index] == NULL){
root->next[index] = new node();
for (int k = 0; k < 26; k++){
root->next[index]->next[k] = NULL;
}
root->next[index]->ch = tolower(c);
if (suffix.size() == 1){
root->next[index]->end = 1;
}
}
suffix.erase(suffix.begin());
insertSuffixIntoTree(root->next[index], suffix);
}
void buildSuffixTree(node* root, string str){
if (root == NULL) cout << "CRAP" << endl;
for (int i = str.size() - 1; i >= 0; i--){
string suffix = str.substr(i);
cout << "suffix is " << suffix << endl;
insertSuffixIntoTree(root, suffix);
}
}
bool checkEmptyVector(node * leaf){
for (int i = 0; i < 26; i++){
if (leaf->next[i] != NULL){
return false;
}
}
return true;
}
void printSuffixTree(node* root, string str){
if (root->end){
cout << str << endl;
}
if (checkEmptyVector(root)){
return;
}
for (int i = 0; i<26; i++){
//cout << "inside for loop, i is " << i << endl;
while (root->next[i]){
str += root->next[i]->ch;
printSuffixTree(root->next[i],str);
break;
}
}
}
int main() {
string str;
node* suffixRoot = new node();
suffixRoot->ch = ' ';
for (int i = 0; i < 26; i++){
suffixRoot->next[i] = NULL;
}
cout << "enter the string" << endl;
cin >> str;
buildSuffixTree(suffixRoot, str);
//string result = findMaxSuffix(suffixRoot,str);
//cout<<"result is "<<result<<endl;
string result = "";
printSuffixTree(suffixRoot,result);
getchar();
return 0;
}