I'm sorting 2 vectors using a vector of index.
the 2 vectors have not the same size. One vector (keys) is size X and the other (descriptors) is size X*128 (one key is parametrized by 128 values).
In order to create the vector of index, I generated a vector of unsigned, and used the iota function to put in this vector [0,1,2,...,X]
then I use the sort function to sort these index depending scale of a key (keys[i].s).
After that, I generate another vector in which I copy the values using the vector of index for both descriptors and keys (calling them descriptors_tmp, and keys_tmp), and then I want to make the first keys vector equal to the keys_tmp, and the same for descriptors equals to descriptors_tmp.
My question are :
-Is there a way to make that without making any copy. Since I don't need the previous version of keys and descriptors, I could just make the vector point on the other vector (something like *keys = *keys_tmp) ?
-Is there an easier way to achieve what I'm trying to achieve?
My code :
void _siftMatch::getIdxOfSorting(std::vector<unsigned>& idx_scale_order)
{
//keys[i].s is the scale and I sort depending decreasing scale
auto cmp_scale = [this](int i, int j) {
return keys[i].s > keys[j].s;
};
std::sort(idx_scale_order.begin(), idx_scale_order.end(), cmp_scale);
}
void _siftMatch::sort() {
//vector containing the index of sorted
std::vector<unsigned>idx_scale_order;
idx_scale_order.resize(keys.size());
//Generate [0,1,...,X]
std::iota(idx_scale_order.begin(), idx_scale_order.end(), 0);
//Sort the vector
getIdxOfSorting(idx_scale_order);
std::vector<float> descriptors_tmp;
std::vector<SiftGPU::SiftKeypoint> keys_tmp;
for (int i = 0; i < idx_scale_order.size(); ++i) {
keys_tmp.push_back(keys[idx_scale_order[i]]);
for (int j = 0; j < 128; ++j)
descriptors_tmp.push_back(descriptors[idx_scale_order[i] * 128 + j]);
}
//This is here that I want to put descriptors_tmp and keys_tmp in descriptors and keys
//descriptors.swap(descriptors_tmp.data);
}
Is there a way to make that without making any copy
This example of sorting 3 arrays according to one of the arrays, using a 4th generated array of indices that are sorted according to one of the 3 arrays may help. The key part of this is the in place reordering of all 4 arrays according to the array of indices. You'll need to modify this for your situation. I'm not sure why you are converting the array of indices to an array of numeric strings (via the itoa calls), using the indices directly works better for the example in this answer.
// sort 3 vectors according to one of them
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
int main()
{
std::vector <int> A; // ages
std::vector <std::string> N; // names
std::vector <int> Z; // zip codes
std::vector <size_t> I; // indices
int tA;
std::string tN;
int tZ;
A.push_back(37);
N.push_back("Ted");
Z.push_back(54211);
A.push_back(21);
N.push_back("John");
Z.push_back(53421);
A.push_back(31);
N.push_back("Fred");
Z.push_back(52422);
A.push_back(21);
N.push_back("Sam");
Z.push_back(51422);
// display the vectors
for(size_t i = 0; i < A.size(); i++)
std::cout << std::setw(6) << N[i]
<< std::setw(8) << Z[i]
<< std::setw(4) << A[i] << std::endl;
std::cout << std::endl;
// initialize the vector of indices
for(size_t i = 0; i < A.size(); i++)
I.push_back(i);
// sort I according to A
std::stable_sort(I.begin(), I.end(),
[&A](size_t i, size_t j) {return
A[i] < A[j];});
// reorder A, N, Z in place also restore I
// time complexity is O(n)
for(size_t i = 0; i < A.size(); i++){
size_t j, k;
if(i != I[i]){
tA = A[i];
tN = N[i];
tZ = Z[i];
k = i;
while(i != (j = I[k])){
A[k] = A[j];
N[k] = N[j];
Z[k] = Z[j];
I[k] = k;
k = j;
}
A[k] = tA;
N[k] = tN;
Z[k] = tZ;
I[k] = k;
}
}
// display the sorted vectors
for(size_t i = 0; i < A.size(); i++)
std::cout << std::setw(6) << N[i]
<< std::setw(8) << Z[i]
<< std::setw(4) << A[i] << std::endl;
return 0;
}
Related
I have no error message instead I only have unexpected behavior.
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
int n = weights.size();
vector<pair<double, int>> valuePerWeight(n);
pair<double,int> x;
for(int i = 0; i < n; i++){
double v = values[i]/weights[i];
x = make_pair(values[i]/weights[i], weights[i]);
valuePerWeight.push_back(x);
}
for(int i = 0; i < n && capacity > 0; i++){
int amount = min(capacity, valuePerWeight[i].second);
value += valuePerWeight[i].first * amount;
capacity -= amount;
}
double value = 0.0;
return value;
}
I am creating a vector with values of type pair<double,int>. I create the pair using make_pair(some_double, some_int), then I call push_back with the pair.
Later in the function I index into the vector and do stuff using the pairs.
However an issue arises, when I index into my valuePerWeight vector and retrieve the attributes of the different pairs. They all end up being zero regardless of index and regardless of .first or .second.
Through printing a bunch of variables I have asserted the created pair is not {0,0} but as soon as I push_back into the vector and index the pair and look at it's .first and .second attributes both are equal to 0.
I can't seem to understand why this is, originally I was using push_back seen as below
valuePerWeight.push_back(make_pair(values[i]/weights[i], weights[i]));
instead of creating into a temporary variable x . However the same issue still stands.
Any help in the right direction would be greatly appreciated.
If there is any further clarification that I can give please ask me.
If you'd like to see for some values below is a snippet which can be compiled
I use input
3 50
60 20
100 50
120 30
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
double value = 0.0;
int n = weights.size();
vector<pair<double, int>> valuePerWeight(n);
pair<double,int> x;
for(int i = 0; i < n; i++){
double v = values[i]/weights[i];
cout << v << ' '<< weights[i] << '\n';
x = make_pair(values[i]/weights[i], weights[i]);
cout << x.first << ' ' << x.second << '\n';
valuePerWeight.push_back(x);
cout << valuePerWeight[i].first << ' ' << valuePerWeight[i].second << '\n';
}
for(int i = 0; i < n; i++){
cout << valuePerWeight[i].first;
cout << valuePerWeight[i].second;
cout << '\n';
}
sort(valuePerWeight.begin(), valuePerWeight.end());
for(int i = 0; i < n && capacity > 0; i++){
int amount = min(capacity, valuePerWeight[i].second);
value += valuePerWeight[i].first * amount;
capacity -= amount;
}
// for(auto vp: valuePerWeight){
// cout << vp.first << vp.second;
// cout << '\n';
// }
return value;
}
int main() {
int n;
int capacity;
std::cin >> n >> capacity;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++) {
std::cin >> values[i] >> weights[i];
}
double optimal_value = get_optimal_value(capacity, weights, values);
std::cout.precision(10);
std::cout << optimal_value << std::endl;
return 0;
}
The confusion here is due to the behavior of the constructor you use
vector<pair<double, int>> valuePerWeight(n);
This actually fills the vector with n default constructed pairs, which as you may surmise, are (0, 0). When you push_back, you push to the end of these, so you a totally get 2n pairs.
.reserve does something close to what you expected, not actually filling the vector, but is likely not needed for something not bottle-necking on vector resizing.
Short story, omit the (n) to just construct an empty vector.
Three more suggestions: accept the vectors as const& to save a copy, and look at emplace_back instead of making a pair yourself and pushing it. That's what it's meant for. Also, note the comment by churill - dividing two integers will result in integer division regardless of where you are assigning the result. Static cast one of them to a float or double (or multiply by 1.0 at the start) to ensure floating point division.
I need to sort negative elements of matrix by scheme below. I've tried to sort from another corner, but it is not working too. I think, that I need to put elems of matrix in 1d array. It should be sorted in Cocktail sort, but sort's type not my main problem.
My code:
int main() {
const int n = 4, m = 4;
int t, v[n*m], arr[n][m], i, j, tmp, lt, rt;
lt = 0;
rt = t;
srand(time(NULL));
for (i = 0; i < n; i++) {
for(j=0; j < m; j++) {
arr[i][j] = rand() % 100 - 50;
}
cout << endl;
}
t = 0;
for (i = 0; i < n; i++) {
for(j = 0; j < m; j++) {
if (arr[i][j] < 0) {
v[t] = arr[i][j];
t++;
}
}
}
while(lt <= rt) {
for (i = rt; i >= lt; i--) {
if(v[i] > v[i-1]) {
swap(v[i], v[i-1]);
}
}
lt++;
for (i = lt; i <=rt; i++) {
if(v[i] > v[i-1]) {
swap(v[i], v[i-1]);
}
}
rt--;
}
for (i = 0; i < t; i++) {
cout << v[i] << " ";
}
int r = 0;
for (i = 0; i < n; i++) {
for(j = 0; j < m; j++) {
if(arr[i][j] < 0) {
arr[i][j] = v[r];
r++;
}
}
}
}
The question sounds easy, but it is not. There is a lot of “indirection” in it, where you need to work with indices instead of values.
I shortly checked you code. It is mostly C–Code (not C++) and buggy.
Example:
int t;
rt = t;
With that you have an uninitialized variable, used as an array index. That is a fatal bug. You are also using VLA’s (Variable Length Array). This is not allowed in C++. And you are using plain C-Style arrays. This you should not do. Use std::vector, which can grow dynamically or at least std::array instead. And please give your variable more meaningful names.
I will show you one (out of the many possible) solutions, but I will use C++.
The core of the problem at hand is to find the row and column indices of the elements in the given matrix. That is not easy.
But ok, let’s start with that. If you draw a picture with the matrix and then add dotted lines over the diagonals, then you see the indices.
If the dimension of the matrix is dim then there are always dim + dim – 1 diagonals. The diagonals have first a rising number of elements and after hitting the main, longest diagonal in the middle, decreasing number of elements. So we iterate over the number of all diagonals, split by the middle diagonal, and calculate the corresponding row and column indices. This is a bit tricky, but after some time you will find out.
The resulting row and column indices will be stored in a struct. All diagonals with all row and column indices will be stored in a vector of struct. Additionally, we add the values of the original matrix cells.
Regarding the sorting. It is obviously your task to develop an own sorting algorithm. For that purpose, I created a function yourSort where you can put in your own algorithm. I simply use standard algorithms (std::sort). You may replace std::sort by your own function.
In main I put some driver code. First, we create a matrix and fill it with random values. Then we calculate the row and column indices. The entries with the negative values will be extracted and sorted. Then we copy the result back to the original matrix.
As said above, not so easy, because of the indirection with the indices and the constraint to use only negative numbers.
But anyway. Please see:
#include <iostream>
#include <vector>
#include <utility>
#include <random>
#include <algorithm>
#include <iterator>
#include <iomanip>
// Create types that are easy to understand
using RowIndex = size_t;
using ColumnIndex = size_t;
// Here we store the position (row and column) and the value of one cell in the matrix
struct PositionAndValue {
// Constructors
PositionAndValue() {};
PositionAndValue(const RowIndex r, const ColumnIndex c, const int v) : rowIndex(r), columnIndex(c), value(v) {};
// Data
RowIndex rowIndex{};
ColumnIndex columnIndex{};
int value{};
};
// Main data types
using Columns = std::vector<int>;
using Matrix = std::vector<Columns>;
using Diagonal = std::vector<PositionAndValue>;
// Fill matrix with random values. Standard function
void fillMatrixRandom(Matrix& m) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(-50, 50);
std::for_each(m.begin(), m.end(), [&](Columns &c) {std::for_each(c.begin(), c.end(), [&](int &j) { j = dis(gen);}); });
}
// Calculate the indices for all diagonals
Diagonal calculateDiagonalIndices(const Matrix& matrix) {
// The return value
Diagonal diagonalIndices{};
// Matrix dimension
const size_t MatrixDimension{ matrix.size() };
// Overall number of diagonals for this matrix
const size_t NumberOfDiagonals{ MatrixDimension + MatrixDimension - 1 };
// index of middle (longest) diagonal
const size_t MiddleDiagonal { NumberOfDiagonals / 2 + 1 };
// Counter for element index in one specific diagonal
size_t elementInDiagonal{ 0 };
for (size_t diagonalIndex = 1; diagonalIndex <= NumberOfDiagonals; ++diagonalIndex) {
// If we are above the middle diagonal
if (diagonalIndex <= MiddleDiagonal) {
// Number of elements in diagonal will increase
++elementInDiagonal;
for (size_t j = 0; j < elementInDiagonal; ++j) {
// Calculate row and column and add to result
const RowIndex row{ j };
const ColumnIndex col{ diagonalIndex - j - 1 };
diagonalIndices.emplace_back(PositionAndValue(row, col, matrix[row][col]));
}
}
else {
// We are below the middle diagonal
// Number of elements in diagonal will decrease
--elementInDiagonal;
for (size_t j = 0; j < elementInDiagonal; ++j) {
// Calculate row and column and add to result
const RowIndex row{ diagonalIndex + j - MatrixDimension };
const ColumnIndex col{ MatrixDimension - j - 1 };
diagonalIndices.emplace_back(PositionAndValue(row, col, matrix[row][col]));
}
}
}
return diagonalIndices;
}
// Simple sorting function using std algorithms
template <typename T, typename ValueType>
void yourSort(std::vector<T>& vec, ValueType T::* mPtr) {
// We will extract the negative values
std::vector<ValueType> vt{};
// Extract
std::transform(vec.begin(), vec.end(), std::back_inserter(vt), [&](const T & s) {return s.*mPtr; });
// Sort. ***** Please put here your sorting function
std::sort(vt.begin(), vt.end());
// Put back
std::for_each(vec.begin(), vec.end(), [&, i = 0U](T& s) mutable{s.*mPtr = vt[i++]; });
}
// Driver code
int main() {
// Lets use a matrix of this size
constexpr size_t MatrixDimension = 4U;
// Small lambda for printing a matrix
auto printMatrix = [](const Matrix & m) {std::for_each(m.begin(), m.end(), [](const Columns & c) {
for (int i : c) std::cout << std::setw(4) << i; std::cout << "\n"; }); std::cout << "\n"; };
// Define a matrix and fill it with random values
Matrix matrix(MatrixDimension, Columns(MatrixDimension));
fillMatrixRandom(matrix);
printMatrix(matrix);
// Calulate the indices on the diagonals
Diagonal diagonal{ calculateDiagonalIndices(matrix) };
// Extract the negatives
Diagonal negativesOnDiagonal{};
std::copy_if(diagonal.begin(), diagonal.end(), std::back_inserter(negativesOnDiagonal),
[](const PositionAndValue & pv) { return pv.value < 0; });
// Sort
yourSort(negativesOnDiagonal, &PositionAndValue::value);
// Copy back
std::for_each(negativesOnDiagonal.begin(), negativesOnDiagonal.end(),
[&matrix](const PositionAndValue & pv) { matrix[pv.rowIndex][pv.columnIndex] = pv.value; });
printMatrix(matrix);
return 0;
}
I am trying to remove the duplicate elements in a sorted vector such that each element appears only once.
My code:
#include <iostream>
#include <vector>
using namespace std;
void removeDuplicates(vector<int> &nums)
{
vector<int>::iterator it;
unsigned int j = 1;
while(j < nums.size()-1)
{
if(nums.at(j) == nums.at(j-1))
{
it = nums.begin()+j;
nums.erase(it);
--j; // for every removal, correct the index
}
j += 1; // increment the index
}
}
int main ()
{
vector <int> vect;
int arr[] = {0,0,1,1,1,1,1,2,2,3,3,4}; // the given array
int arrSize = sizeof(arr)/sizeof(arr[0]);
for (int i = 0; i <= arrSize-1; i++) // assign values to the vector
{
vect.push_back(arr[i]);
}
removeDuplicates(vect);
cout << "The unique vector elements are: ";
for (int i = 0; i < vect.size(); i++)
{
cout << vect[i] << " ";
}
cout << endl;
return 0;
}
When I run the code, the output is
The vector unique elements are: 0 1 2 3 4
The question gives the following instruction:
Do not allocate extra space for another array, you must do this by
modifying the input array in-place with O(1) extra memory.
In my code, the Big O time complexity is O(n).
How can I remove the duplicates in-place with an extra memory of O(1)?
How can remove the duplicates in-place with a time complexity of O(1)?
You can't. Even with the vector sorted, you simply must compare every single element to know whether it is unique or not. O(N) is optimal.
However, O(1) time complexity wasn't required by the task either:
... with O(1) extra memory.
There was no mention of time complexity constraint - only space complexity.
The simplest way to get rid of duplicates is to use what's already available in the standard library:
nums.erase(std::unique(nums.begin(), nums.end()), nums.end());
You can implement it in place (no extra memory) with a complexity O(n) by simply using two indices, one for reading the elements and one for writing.
#include <iostream>
#include <vector>
void removeDuplicates(std::vector<int> &nums)
{
unsigned int j = 1;
for (unsigned int i = 1; i < nums.size(); i++)
{
if(nums.at(i) != nums.at(i-1))
{
nums.at(j++) = nums.at(i);
}
}
nums.resize(j);
}
int main ()
{
std::vector <int> vect;
int arr[] = {0,0,1,1,1,1,1,2,2,3,3,4}; // the given array
int arrSize = sizeof(arr)/sizeof(arr[0]);
for (int i = 0; i <= arrSize-1; i++) // assign values to the vector
{
vect.push_back(arr[i]);
}
removeDuplicates(vect);
std::cout << "The unique vector elements are: ";
for (int i = 0; i < vect.size(); i++) {
std::cout << vect[i] << " ";
}
std::cout << "\n";
return 0;
}
This question already has answers here:
Sorting zipped (locked) containers in C++ using boost or the STL
(5 answers)
Closed 1 year ago.
I have four vectors containing x, y, radius and weight information on centres of circles. I would like to sort them in order of weight (highest to lowest), but I really have no idea how or where to start with this. I could put all the vectors in an Eigen::Tensor to keep the data gathered in one 4d matrix if that would help. But other than that I don't know.
Each of the vectors contain 134 elements, but since it's only one of them having to be sorted that means the sorting algorithm doesn't matter all that much.
Does anyone have a hint on where to start?
You can create a 5th vector of indices, sort the vector of indices according to one of the 4 vectors, then reorder all 4 vectors (and also sort the vector of indices) in O(n) time. Example to sort 3 vectors according to one of them (the ages vector). The vector of indices I is created then sorted according to A (using lambda compare), then all 3 vectors and I are reordered according to I by undoing the "cycles" in I.
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
int main()
{
std::vector <int> A; // ages
std::vector <std::string> N; // names
std::vector <int> Z; // zip codes
std::vector <size_t> I; // indices
int tA;
std::string tN;
int tZ;
A.push_back(37);
N.push_back("Ted");
Z.push_back(54211);
A.push_back(21);
N.push_back("John");
Z.push_back(53421);
A.push_back(31);
N.push_back("Fred");
Z.push_back(52422);
A.push_back(21);
N.push_back("Sam");
Z.push_back(51422);
// display the vectors
for(size_t i = 0; i < A.size(); i++)
std::cout << std::setw(6) << N[i]
<< std::setw(8) << Z[i]
<< std::setw(4) << A[i] << std::endl;
std::cout << std::endl;
// initialize the vector of indices
for(size_t i = 0; i < A.size(); i++)
I.push_back(i);
// sort I according to A
std::stable_sort(I.begin(), I.end(),
[&A](size_t i, size_t j) {return
A[i] < A[j];});
// reorder A, N, Z in place also restore I
// time complexity is O(n)
for(size_t i = 0; i < A.size(); i++){
size_t j, k;
if(i != I[i]){
tA = A[i];
tN = N[i];
tZ = Z[i];
k = i;
while(i != (j = I[k])){
A[k] = A[j];
N[k] = N[j];
Z[k] = Z[j];
I[k] = k;
k = j;
}
A[k] = tA;
N[k] = tN;
Z[k] = tZ;
I[k] = k;
}
}
// display the sorted vectors
for(size_t i = 0; i < A.size(); i++)
std::cout << std::setw(6) << N[i]
<< std::setw(8) << Z[i]
<< std::setw(4) << A[i] << std::endl;
return 0;
}
With ranges-v3, you may do something like
ranges::sort(
ranges::view::zip(xs, ys, radiuses, weights),
std::greater<>{}, // decreasing order
[](const auto& t){ return std::get<3>(t); }); // Projection: use weight
Demo
But having class Circle would make sense, that would avoid to zip the arrays, and allow to have a shorter projection.
Perhaps it makes more sense to first restructure your code and convert four vectors into one vectors of structures.
Something like that:
struct CircleInfo
{
int x, y, radius, weight;
};
std::vector<CircleInfo> circles;
Then, if you want to sort by radius:
#include <vector>
#include <algorithm>
#include <iostream>
struct CircleInfo
{
int x, y, radius, weight;
};
int main()
{
std::vector<CircleInfo> circles;
CircleInfo ci1 = { 1,1,1,1 };
CircleInfo ci2 = { 3,3,3,3 };
circles.push_back(ci2);
circles.push_back(ci1);
std::cout << "before sort circles[0].radius: " << circles[0].radius << std::endl;
std::sort(circles.begin(), circles.end(), [](const CircleInfo& c1, const CircleInfo& c2) {
return c1.radius < c2.radius;
});
std::cout << "aftern sort circles[0].radius: " << circles[0].radius << std::endl;
}
Output:
before sort circles[0].radius: 3
after sort circles[0].radius: 1
This code uses std::sort with custom function that compares two circles. To compare by radius you'd need to update it to compare c1.weight with c2.weight.
I'm trying to pull off a gapped insertion sort in C++, known as a Library sort. I understand the concept, but I'm having trouble pulling it off going from a regular old insertion sort. I don't know how I'd account for the gaps in the array. I've been using the integer 0 to specify a gap. The code I have so far is below, which is a working insertion sort modified abit. How would you go about implementing a library sort? I went through 20 pages of google, and I have not seen a single actual example of code, in any programming language.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
vector<int> librarySort(int arr[20])
{
int j,tmp;
vector<int> array;
for (int i=0;i<20;i++)
{
array.push_back(0);
array.push_back(arr[i]);
}
for (int i=0;i<40;i++) { cout << array[i] << ",";}
cout << endl;
for (int i = 1; i < 40; i++)
{
j = i;
while (j > 0 && array[j - 1] > array[j])
{
tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
j--;
}
}
for (int i=0;i<40;i++) { cout << array[i] << ",";}
return array;
}
int main()
{
srand(time(0));
int array[20]= {0};
for (int i=0;i<20;i++)
{
int n=rand()%19+1;
tmp=array[i];
array[i]=array[n];
array[n]=tmp;
}
for (int i=0;i<20;i++) { cout << array[i] << ",";}
cout << endl;
librarySort(array);
}
Here you have a complete description and implementation. The gap is defined as whatever value that you will not use. If you were using pointers, NULL is a good option.
In general cases you must create an auxiliary array to the one that has the original data. In this case:
#define MAX 20
#define MAX2 100//The size of the gapped array must be bigger
#define EMPTY -1//Use this constant instead of zeros.
bool isEmpty(int index, int gappedArray[MAX2]) {
return gappedArray[index]>=0;
}
vector<int> libSort(int arr[MAX]) {
int aux[MAX];
for(int i=0;i<MAX;i++) aux = i;
//Add your library sort algorithm here
//However instead of comparing arr[i] with arr[j], compare arr[aux[i]] with arr[aux[j]]
//Then, when you are going to insert sorted values, insert aux[pos], not arr[pos]
}
Here you have library sort pseudocode:
Rebalance(Array S, Integer iniLen, Integer finLen)
k = finLen-1
step = finLen/iniLen
for j=iniLen-1 to 0:
S[k] = S[j]
S[j] = NONE
k = k-step
end for
LibrarySort(Array A, Integer n, Float epsilon, Array S)
goal = 1
pos = 0
sLen = (Integer)(1+epsilon)*n
while pos<n://For each round do this:
for i=1 to goal://Insert 'goal' elements to the sorted array S
//Search a position to insert A[pos]
insPos = binarySearch(A[pos], S, sLen)
if not IS_EMPTY(S[insPos]):
//Move elements to the right or the left in order to free
//insPos
freeSpace(insPos, S, sLen)
end if
S[insPos] = A[pos]//Insert new element
pos = pos + 1
if pos>n://All elements have been inserted
return LibrarySort
end if
end for
prevLen = sLen
sLen = min( (2+2*epsilon)*goal, (1+epsilon)*n )
//Rebalance array S
Rebalance(S, prevLen, sLen)
goal = goal * 2
end while