c++ – How does boost sort handle additional memory allocation

According to the documentation of boost::sort (https://www.boost.org/doc/libs/1_75_0/libs/sort/doc/html/index.html) all algorithms uses “additional memory“.

I couldn’t find any information on how this memory is allocated in the documentation.

Does anyone know if it is heap-allocated during each sort operation, is it stack-space, or does boost::sort utilize some static internal memory buffer (like std::stable_sort)?

If heap-allocated, is it possible to pass a pre-allocated buffer to the sort operations in order to gain control over memory allocations?

How to automatically fill, sort and conditionally format 1st day of the week according to given year and month in excell?

I previously had the answer in Google sheet environment
How to automatically fill, sort and conditionally format 1st day of the week according to given year and month. I would like to do it in Excel but the function (sequence) is not valid .. Any thoughts?

java – Find Least Number of Swaps to Sort List

Here is my (working) code that finds the least number of swaps to sort a list in ascending order.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Sort_Swap {
    public static void main(String() args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        sc.close();
        List<Integer> int_list = new ArrayList<Integer>();
        List<Integer> sorted_int_list = new ArrayList<Integer>();
        String() str_list = input.split("");
        for (int i = 0; i < str_list.length; i ++) {
            int_list.add(Integer.parseInt(str_list(i)));
        }
        System.out.println(int_list + "n");
        int swap_num = 0;
        for (int n = 0; n < int_list.size(); n ++) {
            if (int_list.get(n) == 1) {
                sorted_int_list.add(1);
            }
        }
        for (int n = 0; n < int_list.size(); n ++) {
            if (int_list.get(n) == 2) {
                sorted_int_list.add(2);
            }
        }
    
        for (int n = 0; n < int_list.size(); n ++) {
            if (int_list.get(n) == 3) {
                sorted_int_list.add(3);
            }
        }
        System.out.println(sorted_int_list);
        for (int x = 0; x < int_list.size(); x++) {
            if (int_list.get(x) != sorted_int_list.get(x)) {
                for (int y = int_list.size() - 1; y >= 0; y--) {
                    if (sorted_int_list.get(x) == int_list.get(y)) {
                        int_list.set(y, int_list.get(x));
                        int_list.set(x, sorted_int_list.get(x));
                        swap_num ++;
                        System.out.println(int_list);
                        break;
                    }
                }
            }
        }
        System.out.println("Least # of swaps: " + swap_num);
    }
}

The input is just one, two, or three (Eg. ‘213212’ or ‘321’). The way that I found the least number of swaps is by comparing the unsorted list to sorted list. It finds the nth index and sees if it matches the nth index of the sorted list. If not, then it finds the farthest element (by looping backwards) that it should be equal to in the unsorted list, and it is then swapped. For example: suppose we have an unsorted and sorted list:

(3,2,2,3,1)

(1,2,2,3,3)

In index 0, the unsorted list should be equal to 1, so it finds the farthest 1 in the unsorted list, and swaps it. Here’s a sample output:

Input: 232123
(2, 3, 2, 1, 2, 3)
(1, 2, 2, 2, 3, 3)

(1, 3, 2, 2, 2, 3)
(1, 2, 2, 2, 3, 3)
Least # of swaps: 2

2 is indeed the least number of swaps. However, this code is very inefficient for very large inputs. I first sorted the list with a bubble sort, however I changed the way I sorted my list and reduced it to O(n) by just adding all the 1s first, then 2s, and then 3s. But is there a way to increase the efficieny of my code? Because the algorithm that finds the least number of swaps has a time and space complexity of O(n^2). Is there anyway I could make my code more efficient and decrease my time and space complexity? Perhaps there is a better way to code the algorithm? Or perhaps my approach was wrong entirely?

python – Making This “Fancy” Sort Algorithm a Little Better

This is my code:

def add_to_destination_array(destination_arr, src1, iSrc1, src2, iSrc2):
    temp_array_length = len(destination_arr)
    while len(destination_arr) - temp_array_length < len(src1) + len(src2):
        if iSrc1 < len(src1):
            if iSrc2 == len(src2):
                destination_arr.append(src1(iSrc1))
                iSrc1 += 1
            else:
                if src1(iSrc1) <= src2(iSrc2):
                    destination_arr.append(src1(iSrc1))
                    iSrc1 += 1
                elif src2(iSrc2) <= src1(iSrc1):
                    destination_arr.append(src2(iSrc2))
                    iSrc2 += 1
        elif iSrc2 < len(src2):
            if iSrc1 == len(src1):
                destination_arr.append(src2(iSrc2))
                iSrc2 += 1
            else:
                if src2(iSrc2) <= src1(iSrc1):
                    destination_arr.append(src2(iSrc2))
                    iSrc2 += 1
                elif src1(iSrc1) <= src2(iSrc2):
                    destination_arr.append(src1(iSrc1))
                    iSrc1 += 1


def fancy_sort(array_to_sort):
    destination_array = ()
    source1 = (array_to_sort(0))
    source2 = ()
    iSource1 = 0
    iSource2 = 0
    got_first_sublist = False
    first_sublist_start = 0
    second_sublist_start = 0
    array_sorted = False

    for i in range(1, len(array_to_sort)):
        if len(source1) == 0:
            source1.append(array_to_sort(i))
            first_sublist_start = i
        elif not got_first_sublist:
            if source1(i-first_sublist_start-1) <= array_to_sort(i):
                # Add elements to the first sublist
                source1.append(array_to_sort(i))
            else:
                # First sublist found, now we start finding the seconds sublist
                source2.append(array_to_sort(i))
                second_sublist_start = i
                got_first_sublist = True
        else:
            if source2(i-second_sublist_start-1) <= array_to_sort(i):
                # Add elements to the second sublist
                source2.append(array_to_sort(i))
            else:
                # Start adding elements to the destination_array
                add_to_destination_array(destination_array, source1, iSource1, source2, iSource2)
                
                # Reset the variables and start over
                first_sublist_start = i
                source1 = (array_to_sort(i))
                source2 = ()
                iSource1 = 0
                iSource2 = 0
                got_first_sublist = False
    
    # If it didn't completely finish "sorting"
    if len(source1) > 0:
        if len(source1) == len(array_to_sort):
            array_sorted = True
        elif len(source2) > 0:
            add_to_destination_array(destination_array, source1, iSource1, source2, iSource2)
        else:
            for i in source1:
                destination_array.append(i)
    
    # Call the function again to continue sorting
    if not array_sorted:
        return fancy_sort(destination_array)
    return array_to_sort

sorting_array = (31, 72, 32, 10, 95, 50, 25, 18)


print(f"Before: {sorting_array}")

sorted_array = fancy_sort(sorting_array)

print(f"After:  {sorted_array}")

I know it’s not the best, but it still works. This algorithm is supposed to be similar to the merge sort, but it doesn’t really split the array, and then merges them together. This algorith is supposed to find two already sorted sub-arrays (or sub-lists if you want to call it that), and then “merge” them into another array (called the destination array).

Here is the info I was given to make create this algorithm:

Algorithm in Plain English
A teacher is trying to alphabetize a collection of papers. She picks up the papers in her hand and, starting at the top of her stack, works her way down until she finds the first paper out of order. That sub-stack is sorted, and is set aside. She does the same thing to find the next sorted sub-stack. These two sub-stacks are then combined into a single sorted stack that she places on the table. She continues through the original stack in her hand, combining pairs of sorted sub-stacks and putting the results on top of the stack on the table. When she is finished, only the stack on the table remains. Now she picks up the stack on the table and again searches for sorted sub-stacks. When she finds a pair of these, they are combined and placed on the table again. This process continues until again all the papers are on the table. When she picks the stack up off of the table and everything is sorted (there is only one sorted sub-stack), then she is done!

Detailed Description of the Algorithm
Start at the beginning of the array and continue until you discover the first element that is not in sorted order. This sub-array may consist of one element, or it may consist of hundreds. We will call this sub-array source1. Now, starting in the slot after source1, find the next sub-array. Again, this may consist of one element or hundreds. We will call this sub-array source2. Note that source1 and source2 are sorted individually. These two sub-arrays correspond to the small piles in the previous paragraph.

Now we will combine these two sub-arrays to form a single sorted sub-array. We will not do this in place. Instead, we will move them into a new sub-array called destination. Now since the two source arrays are sorted, we can assume that the smallest element in the two arrays is at the beginning of one of the two source arrays. In other words, it is at source1(0) or source2(0). Therefore destination(0) must be filled with either source1(0) or source2(0). If, for example, source2 has the lower of the two elements, then that element is moved to destination and the index of source2 (which we will call iSource2) is incremented by one. This process is continued until each element from source1 and source2 is moved into destination.

Once the first two sorted sub-arrays are moved to the destination array, then the next two sub-arrays are identified and combined into the destination array. This process continues until each element in the source array is moved into the destination array. Here, we can say that we have completed one pass of the source array.

Note that the sort is not finished yet. We have not sorted the array when we have completed just one pass. The only thing that a single pass accomplishes is to double the size of the sorted sub-arrays. We have to do many passes until the entire destination array becomes a single sorted sub-array. At that point, we can say that the array is sorted.

enter image description here

I am really wanting to go down to just using the array_to_sort and destination_array and then just use the indices for the other stuff instead of the two different source arrays.

Here is a working example.

google sheets – How to sort number in the form of 00-00?

I am trying to sort rows by the number of rooms:

1-1
11-1
11-8
12-5
13-1
2
5-5

When sorting these rows in an ascending order, it always give wrong order even if I add 0 before every single digit

https://docs.google.com/spreadsheets/d/1D6q7IsdAIIgD-9GuMNSdLhBVDOtKniDW_cy-Td0Sq_I/edit#gid=1162496797

I tried to make a helper column by adding =arrayformula(text(B1:B,"00"))
Also tried to add 0 in front of every number by =arrayformula(0&B5:B). But all didn’t work

sorting – Sort items so that parents are created before their children

I’ve been asked to create some code to help automate the loading of data into a system based on employee data in a spreadsheet. However, the data isn’t clean, so some people may have no manager, some may be their own manager, some have managers who already exist in the system, so aren’t included in the export, and others managers are somewhere in the export.

The below sort algorithm is to allow a sort of such dirty data, to ensure that where a dependency chain can be resolved it is and the items are returned in the appropriate order; but if the data’s bad, we’ll still be able to do as much good as possible.

Sharing it here as there may be a more efficient solution. I’ve seem similar solutions which build a tree then traverse it; but all those I’ve seen require clean data to function correct, and I can’t think of a way to amend them whilst keeping their efficiency.

Function Sort-ParentChild {
    (CmdletBinding())
    Param (
        (Parameter(Mandatory, ValueFromPipeline))
        (PSCustomObject())$ListItems
        ,
        (Parameter(Mandatory))
        (string)$ParentPropertyName
        ,
        (Parameter(Mandatory))
        (string)$CurrentPropertyName
    )
    Begin {
        (System.Collections.Generic.List(PSCustomObject))$Pending = (System.Collections.Generic.List(PSCustomObject))::new()
    }
    Process {
        foreach ($item in $ListItems) {
            # first return items which have no parent, or which are their own parent (since circular dependencies would otherwise never be resolved
            if (($null -eq $item."$ParentPropertyName") -or (($item."$CurrentPropertyName" -eq $item."$ParentPropertyName"))) {
                $item
            } else {
                $Pending.Add($item)
            }
        }
    }
    End {
        while ($Pending.Count) {
            $circularLoop = $true
            # return any items whose parents are not in the pending list (i.e. they already existed so weren't in the todo list, or we've returned them earlier in the process)
            for ($i = ($Pending.Count-1); $i -ge 0; $i--) { # work down, so that removing an item won't have any odd impacts
                if ($Pending($i)."$ParentPropertyName" -notin @($Pending | Select-Object -ExpandProperty $CurrentPropertyName)) {
                    $Pending($i)
                    $Pending.RemoveAt($i)
                    $circularLoop = $false # if we've found something to return, we're not in a loop yet
                }
            }
            if ($circularLoop) {
                # in case there are any circular dependencies, to avoid getting stuck, return a single item, then try to unravel in dependency order from there
                Write-Warning "Circular dependency found; breaking loop by returning $($Pending(0)."$CurrentPropertyName")"
                $Pending(0)
                $Pending.RemoveAt(0)
            }
        }
    }
}

Example Usage

$users = @(
    @{Id = 'Subordinate17';   ManagerId = 'MiddleManager1'}      
    @{Id = 'Subordinate15';   ManagerId = 'MiddleManager1'}   
    @{Id = 'Subordinate14';   ManagerId = 'MiddleManager3'}   
    @{Id = 'Subordinate13';   ManagerId = 'MiddleManager1'}   
    @{Id = 'TopDog';          ManagerId = $null}      # this person's the top dog; they don't have a manager
    @{Id = 'MiddleManager1';  ManagerId = 'BigBoss1'}
    @{Id = 'BigBoss1';        ManagerId = 'BigBoss1'} # Big Boss is their own boss
    @{Id = 'AmbassadorX';     ManagerId = 'PilotX'}        
    @{Id = 'MiddleManager2';  ManagerId = 'BigBoss1'}
    @{Id = 'PilotX';          ManagerId = 'InstructorX'}   
    @{Id = 'Subordinate17';   ManagerId = 'MiddleManager1'}      
    @{Id = 'MiddleManager3';  ManagerId = 'TopDog'}
    @{Id = 'Subordinate16';   ManagerId = 'MiddleManager3'}      
    @{Id = 'Mya';             ManagerId = 'PilotX'}         
    @{Id = 'Subordinate12';   ManagerId = 'MiddleManager2'}      
    @{Id = 'Subordinate11';   ManagerId = 'MiddleManager1'}      
    @{Id = 'InstructorX';     ManagerId = 'AmbassadorX'}
    @{Id = 'Subordinate10';   ManagerId = 'MiddleManager2'}   
    @{Id = 'Subordinate09';   ManagerId = 'MiddleManager2'}   
    @{Id = 'Subordinate08';   ManagerId = 'MiddleManager2'}   
    @{Id = 'Subordinate07';   ManagerId = 'MiddleManager2'}   
    @{Id = 'Subordinate06';   ManagerId = 'MiddleManager2'}   
    @{Id = 'Subordinate05';   ManagerId = 'TopDog'}   
    @{Id = 'Subordinate04';   ManagerId = 'BigBoss1'}   
    @{Id = 'Subordinate03';   ManagerId = 'MiddleManager3'}   
    @{Id = 'Shark';           ManagerId = $null}           # alone shark :S
    @{Id = 'Subordinate02';   ManagerId = 'MiddleManager3'}   
    @{Id = 'Subordinate01';   ManagerId = 'MiddleManager3'}
) | %{(pscustomobject)$_} #| Sort -Property @{E={(Guid)::NewGuid()}} # optional chaos sort, to avoid any chance of my data being in some helpful order before testing

$users | Sort-ParentChild -ParentPropertyName 'ManagerId' -CurrentPropertyName 'Id'
WARNING: Circular dependency found; breaking loop by returning AmbassadorX
Id             ManagerId     
--             ---------     
TopDog                       
BigBoss1       BigBoss1      
Shark                        
Subordinate04  BigBoss1      
Subordinate05  TopDog        
MiddleManager3 TopDog        
MiddleManager2 BigBoss1      
MiddleManager1 BigBoss1      
Subordinate13  MiddleManager1
Subordinate14  MiddleManager3
Subordinate15  MiddleManager1
Subordinate17  MiddleManager1
Subordinate01  MiddleManager3
Subordinate02  MiddleManager3
Subordinate03  MiddleManager3
Subordinate06  MiddleManager2
Subordinate07  MiddleManager2
Subordinate08  MiddleManager2
Subordinate09  MiddleManager2
Subordinate10  MiddleManager2
Subordinate11  MiddleManager1
Subordinate12  MiddleManager2
Subordinate16  MiddleManager3
Subordinate17  MiddleManager1
AmbassadorX    PilotX        
InstructorX    AmbassadorX   
PilotX         InstructorX   
Mya            PilotX  

algorithms – Insertion Sort vs Merge Sort which is faster depending on array?

Suppose that we are given an array A already sorted in increasing order.
Which is asymptomatically faster, insertion-sort or merge-sort?

Like wise, suppose we are given an array B sorted in decreasing order, so it needs to be reversed. Which is now asymptomatically faster?

Im having a hard time grasping this, i already know that insertion-sort is better for smaller data sets and merge-sort is better for larger data sets. However im not sure why one is faster than the other depending on whether or not the data set is already sorted or not.