Arranging words in alphabetical order - c++

This is my implementation , i have a txt file where the animals are randomly assign. i want to order them and insert it into a list.
void SortedList::insert(std::string x){
int insertPoint=0;
if(top==n){
n = 2 * n;
string* temp = arr;
arr = new string[n];
for (int i = 0; i < top; i++){
arr[i] = temp[i];
}
delete[] temp;
}
arr[top]=x;
LinearOrdering();
top++;
}
and
void SortedList::LinearOrdering(){
for(int i=0; i < top ; i++){
if (arr[i] > arr[ i + 1]) {
swap (arr[i], arr[i+1]);
}
}
}
this is my result
aardvark
baboon
cougar
gorilla
lion
mouse
ocelot
gerbil
orangutan
hamster
panther
elephant
rat
rhinoceros
tiger
hippopotamus
zebra
what wrong with my code that make it partially ordered.

It looks like you're trying to bubble-sort the list. You will have to loop more than once to make it work.
This answer assumes you're doing this for educational purposes. Otherwise, as StilesCrisis suggests, use std::sort() and also you might prefer std::vector<std::string> instead of a string*.

LinearOrdering does not sort the data, it just swaps some elements around.
Save yourself some trouble and call std::sort.

problem is with your linearordering function
oid SortedList::LinearOrdering(){
for(int i=0; i < top ; i++){
if (arr[i] > arr[top]) {
swap (arr[i], arr[top]);
break;
}
}
}

Related

Array Sorting Issues in C++

I am trying to make a program that sorts an array without using the sort function (that won't work with objects or structs). I have made the greater than one work, but the less than one keeps changing the greatest element in the array to a one and sorting it wrong, and when used with the greater than function, the first element is turned into a large number. Can someone please help me fix this or is it my compiler.
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++) {
for(int i = 0; i < size; i++) {
if(array[i] > array[i+1]){
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
}
}
You are not looping correctly. Looks like you are trying bubble sort which is:
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++)
for(int i = k+1; i < size; i++)
if(array[i] < array[k]){
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
void min_sort(int array[], const unsigned int size)
{
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-1-i;j++)
{
if(array[j]>array[j+1])
{
swap(array[j] , array[j+1]);
}
}
}
}
I see that you are trying to implement the bubble sort algorithm. I have posted the code for bubble sort here. In bubble sort you basically compare the element at an index j and the element next to it at index j+1. If array[j] is greater than array[j+1] , you swap them using the swap() function or by using the temp method. The outer loop will run size - 1 times , and the inner loop will run size - 1 - i times because the last element will already be in place.
For Example we have an array of size 4 with elements such as :
array[i] = [100,90,8,10]
The bubble sort will sort it in the following steps :
90,100,8,10
90,8,100,10
90,8,10,100
8,90,10,100
8,10,90,100
8,10,90,100
See, the use of size-1-i . You can see the nested loop runs less number of times in each iteration of the outer loop.
There is only one mistake that your 2nd loop condition should be: i < size -1.
So it should be:
for (int i = 0; i < size -1; i++)
Your attempt at bubble sort is basically correct, you just have an out of bounds issue with your inner loop. During the inner loop's last run, i == size - 1, therefore i + 1 is equal to size, thus data[i+1] is out of range. Simply change the condition of your for to be i < size - 1.
Working example: https://godbolt.org/z/e5ohWPfTz

How can I shuffle a list

this code is for a game I create in unity. I have a list with 100 elements of coordinates and I want to instantiate boxes to them. The Amount of boxes should be 50% and totaly random. If I run my script, I get 50% of the boxes but in the default order. My script don't shuffle the elements in the list. Thanks for help!
// List has 100 elements of coordinates ( x & y)
public List<Vector2> ListPosBoxes = new List<Vector2>();
// Start
void Start()
{
AmountOfBoxes(ListPosBoxes);
}
// Method to display 50% shuffled boxes
void AmountOfBoxes(List<Vector2> list)
{
// Take list -> shuffle -> new list
list = ShuffleList(list);
for (int i = 0; i < list.Count/2; i++)
{
// Create Box
BoxGenerator(list[i]);
}
}
// Method to suffle list
List<Vector2> ShuffleList(List<Vector2> list)
{
Vector2 tmp;
// fisher–yates shuffle
for (int i = list.Count; i < 1; i--)
{
// Pick random Element
int j = Random.Range(0, list.Count);
// Swap Elements
tmp = list[j];
list[j] = list[i - 1];
list[i - 1] = tmp;
}
return list;
}
// Method to create Box
void BoxGenerator(Vector2 box)
{
CreateBox(box.x, box.y);
}
The problem is: the list isn't mixed.
You are running your for-loop from high numbers and decrease i.
// fisher–yates shuffle
for (int i = list.Count; i < 1; i--)
But the test in the for loop is i smaller than 1 so it never runs. Place a Debug.Log in the for-loop to test and flip the operator
I think the problem is that you are trying to re-declare a parameter.
For more info: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
Perhaps start with:
void AmountOfBoxes(List<Vector2> list)
{
// Take list -> shuffle -> new list
shuffled_list = ShuffleList(list);
for (int i = 0; i < list.Count/2; i++)
{
// Create Box
BoxGenerator(shuffled_list[i]);
}
}
// Method to suffle list
List<Vector2> ShuffleList(List<Vector2> list)
{
Vector2 tmp;
list *= list;
// fisher–yates shuffle
for (int i = list.Count; i < 1; i--)
{
// Pick random Element
int j = Random.Range(0, list.Count);
// Swap Elements
tmp = list[j];
list[j] = list[i - 1];
list[i - 1] = tmp;
}
return list;
}
I hope this helps.
What could also help you with debugging, is logging your variables someplace so that you know where it went wrong.
You have a couple of mistakes actually as mentioned in the previous answers but first of all, that Random.Range(0, list.Count); is quite biased actually, please check this link to have a better understanding of why.
And here is the corrected code:
// fisher–yates shuffle
for (int i = 0; i < list.Count; i++) {
// Pick random Element
int j = Random.Range(i, list.Count);
// Swap Elements
Vector2 tmp = list[i];
list[i] = list[j];
list[j] = tmp;
}

C++ Merge Sort Visualizer

I am trying to make a c++ console application that tries to show you how merge sort looks like. I understand merge sort, and I created a program that organizes a vector of strings called sort_visualize, and each string in it is filled with many #. This is completely randomized for every string. The merge sort will organize them depending on length, instead of the traditional number organizing people do with it. Every time I make a change to the vector, I also clear the screen and print out the entire vector through a draw function, to give the effect of it actively visualizing the sort every frame. The problem is that when I use the draw function to print out the entire sort_visualize string, it does not print out any changes that I have made to it, and prints out the same thing over and over again until the end, when it finally prints the sorted order. What is going on? I Don't understand. I even tried changing the draw(sort_visualize) to draw(sort_visualize_), and that shows small areas of the vector it is working on. Makes no sense. Please try this code and tell me any solutions. Thank you.
Here's the code:
#include <vector>
#include <iostream>
#include <ctime>
#include "stdlib.h"
#include "windows.h"
using namespace std;
void merge_sort(vector<string> &sort_visual_);
void merge_halves(vector<string>&left, vector<string>& right, vector<string>& sort_visual_);
void draw(vector <string> &sort_visual_);
vector <string> sort_visual;
int main()
{
srand(time(NULL));
//vector
vector<int> num_list;
//fill vector with random integers
for (int i = 0; i < 40; i++)
num_list.push_back(rand() % 40);
//Fill the visualizer strings which will be bars with #'s
for (int i = 0; i < num_list.size(); i++)
{
sort_visual.push_back("");
string temp;
for (int j = 0; j < num_list.at(i); j++)
{
temp.push_back('#');
}
sort_visual.at(i) = temp;
}
draw(sort_visual);
system("pause");
//sort function
merge_sort(sort_visual);
}
void merge_sort(vector<string> &sort_visual_)
{
//dont do anything if the size of vector is 0 or 1.
if (sort_visual_.size() <= 1) return;
//middle of vector is size/2
int mid = sort_visual_.size() / 2;
//2 vectors created for left half and right half
vector<string> left;
vector<string> right;
//divided vectors
for (int j = 0; j < mid; j++)
{
left.push_back(sort_visual_[j]); //add all the elements from left side of original vector into the left vector
}
for (int j = 0; j < (sort_visual_.size()) - mid; j++)
{
right.push_back(sort_visual_[mid + j]);//add all the elements from right side of original vector into the right vector
}
//recursive function for dividing the left and right vectors until they are length of 1
merge_sort(left);
merge_sort(right);
//do the actual merging function
merge_halves(left, right, sort_visual_);
}
void merge_halves(vector<string>&left, vector<string>&right, vector<string>& sort_visual_) //pass in 3 vectors
{
// sizes of each vector (left and right)
int nL = left.size();
int nR = right.size();
//declaring variables pointint to elements for each vector. i will represent finished produce vector
int i = 0, j = 0, k = 0;
//as long as j and k are less than the left and right sizes
while (j < nL && k < nR)
{
if (left[j].length() < right[k].length()) //if the string in the left vector is smaller than string in right vector
{
sort_visual_[i] = left[j];//ad the string from left vector in the sort_visuals vector(which is the final product)
j++;//increment j to move on
}
else
{
sort_visual_[i] = right[k];//otherwise add the string from right vector in the sort_visual vector
k++; //increment k to move on
}
i++; //i is the final vector, and we have to increment it to set it up to take in the next number
system("CLS");
draw(sort_visual);
Sleep(15);
}
while (j < nL)
{
sort_visual_[i] = left[j];
j++; i++;
system("CLS");
draw(sort_visual);
Sleep(15);
}
while (k < nR)
{
sort_visual_[i] = right[k];
k++; i++;
system("CLS");
draw(sort_visual);
Sleep(15);
}
}
void draw(vector <string> &sort_visual)
{
for (int i = 0; i < sort_visual.size(); i++)
{
cout << sort_visual.at(i) << endl;
}
}
In merge_halves you work on sort_visual_ but draw sort_visual which is a global that does not seem to be changed. Make sure there are no globals and it will be harder to make mistakes.

Sort with no repeat in c++

I am a beginner in C++. I typed a simple code to sort an integer array, but I couldn't figure out how to handle same elements like if I enter 1,12,3,5,11,3
output is given as 1,3,3,5,11,12 but I want the output to be 1,3,5,11,12.
What should I add further in the loop I've coded?
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(array[i]>array[j])
{
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
If you really want to write it by yourself, do as they told you in comments.
If you just want to have a sorted list without duplicates, use std::set and insert all your numbers inside. You will get a sorted, unique list of ints.
It may be easier for you to understand this solution:
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(array[i]>array[j])
{
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
cout<<array[0];
for(int i=1; i<len; ++i)
{
if(array[i] != array[i-1])
{
cout<<array[i];
}
}
Normal way :
Remove the duplicates from the array that you've sorted
int *start = array;
int *end = array+len;
int *res = start;
while (++start != end) {
if (!(*res == *start)) {
*(++res) = *start;
}
}
int new_len=++res -array;
Else why not simply use STL ?
std::sort(array,array+len);
int *res=std::unique(array,array+len);
int new_len=res -array;

Insert values from one array to another directly sorted

So what I have to do is insert certain values from one array to another one directly sorted without having to sort them later using BubbleSort or QuickSort or any other method. I can't think of a way to do this... I have to insert them from the biggest value to the smallest one. Here's what I have until now:
void palindroame (int x[100], int y[100]) {
int i=0, j, k=0, aux;
while (x[i]!=0) {
k++; i++;
}
i=0;
for (i=0; i<=k-1; i++) y[i]=0;
for (i=0; i<=k-1; i++) {
if (palindrom(x[i])!=0 && palindrom(x[i+1])!=0)
if (x[i]<x[i+1]) {
aux=x[i+1]; x[i+1]=x[i]; x[i]=aux;
}
} //wrong
for (i=0; i<=k-1; i++) {
if (palindrom(x[i])) y[i]=x[i];
} //wrong
}
Thanks in advance!
The algorithm you need is selection sort, you can use this to sort and copy at the same time.
You can have a look at priority queues:
http://www.cplusplus.com/reference/queue/priority_queue/
Heres an example of a selection sort i have done recently (in which a is a vector)
should give you enough to go on hope it helps, ask questions if u like
for (unsigned int i = 0; i < a.size()-1; i++)
{
int min = i;
for(unsigned int j = i +1; j < a.size(); j++)
{
// If new minimum is found then stores this as the new minimum
if(a[j] < a[min])
{
min = j;
}
}
// Stores the values in the array in ascending order
if (min != i)
{
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
// Returns the array in ascending order
return a;
Edit: just to clarify this is working on a vector that already has values in it in case that wasnt clear but example with code comments i think is enough to help you IMO