## Linear algorithm to measure how sorted an array is

I’ve just attended an algorithm course, in which I’ve seen many sorting algorithms performing better or worse depending on how much the elements of an array are sorted already. The typical example are quicksort, performing in $$O(n^2)$$ time, and mergesort which operates in linear time on sorted arrays. Vice versa, quicksort performs better in case we are dealing with an array sorted from the highest to the lowest value.

My question is if there is a way to measure in linear time how sorted the array is, and then decide which algorithm is better to use.

## Sorting almost sorted array

Encountered this question but I couldn’t solve with the complexity they solved it:

Suppose I have an array that the first and last $$\sqrt[\leftroot{-2}\uproot{2}]{n}$$ elements has $$\frac{n}{5}$$ swapped pairs, and the middle $$n – 2\sqrt[\leftroot{-2}\uproot{2}]{n}$$ elemnts are sorted. What is the complexity of sorting the unsorted array?

They claim in the answer that sorting array with $$I$$ swaps is $$O(n\log{\frac{n}{I}})$$.Why?

## How can merging two sorted arrays of N items require at least 2N – 1 comparisons in every case?

The HW question, on page 362 of Data Structures and Algorithms in C++: Fourth Editionby Mark Allen Weiss, reads as follows:

Prove that merging two sorted arrays of N items requires at least 2 * N – 1 comparisons. You must show that if two elements in the merged lists are consecutive and from different lists, then they must be compared

If we are trying to find the lower bound then wouldn’t the number of comparisons be N, not 2 * N – 1? If the largest element is some array Ais smaller than the smallest element in some array B then at most you would only have to do N comparisons since after all of A‘s elements are placed in the merged array then the remaining elements in B‘s can simply be appended in to the merged array.

The lower bound has to be something that is true for every possible N and every possible combination of elements in both arrays, right? 2 * N – 1 seems more like it would be the upper bound since there is no way there can be more comparisons than that.

Note: I am not asking for an answer to the HW question itself as I know that is deprecated. I am confused about the implied assertion the question is making about the lower bound

## Pagination on grouped / multi sorted lists

I’m currently working on a design for data heavy lists. User research showed, that users would group / multi sort those lists. this would result in a list with small header rows in between for every sort parameter.

So far so good. I’m now having a hard time, as those lists have a pagination. I would now also need to show the grouped rows over all pages which might take the user out of context…

any thoughts on how to solve the problem?

Cobo

## Find two numbers in sorted array whose product is close to N

Given a sorted array of numbers, is there a good algorithm for finding two numbers in that array whose product is as close as possible to a given number N?

I know that there is a good O(n) (?) algorithm for the related problem of finding two numbers that sum to a given number N. You begin with ptr1 at the start of the array and ptr2 at the end, and if *ptr1 + *ptr2 > N you decrement ptr2, else increment ptr1.

But for multiplication, it feels possible this method could “miss” the optimal solution by overshooting it somehow? Is there a good way to solve the multiplication variant in something that isn’t just O(n^2)?

## Iterate cartesian product (cross product) of sorted lists of positive numbers in order of decreasing product of entries (MVCE of a stub included)

Suppose I have several sorted lists of positive numbers, like so for example:

double[] a1 = new double[]{0.70, 0.20, 0.10}; double[] a2 = new double[]{0.80, 0.10, 0.05, 0.05}; double[] a3 = new double[]{0.60, 0.15, 0.14, 0.10, 0.01}; 

I want to iterate Cartesian product of these arrays in the order of decreasing product of entries, like so:

0000: Combo[product=3.36e-01, vals=[0.70, 0.80, 0.60], indexes=[0, 0, 0]] 0001: Combo[product=9.60e-02, vals=[0.20, 0.80, 0.60], indexes=[1, 0, 0]] 0002: Combo[product=8.40e-02, vals=[0.70, 0.80, 0.15], indexes=[0, 0, 1]] 0003: Combo[product=7.84e-02, vals=[0.70, 0.80, 0.14], indexes=[0, 0, 2]] 0004: Combo[product=5.60e-02, vals=[0.70, 0.80, 0.10], indexes=[0, 0, 3]] 0005: Combo[product=4.80e-02, vals=[0.10, 0.80, 0.60], indexes=[2, 0, 0]] ... 

E.g. in the example above the first entry is obvious (as arrays are sorted) and it is a combination of the first values: [0.70, 0.80, 0.60] with product 0.70*0.80*0.60 = 3.36e-01 and corresponding value indexes in arrays a1, a2, a3 are [0, 0, 0]. Now the second entry is less obvious, should we change 0.70 to 0.20? Or 0.60 to 0.15? Or 0.80 to 0.10? The second should be [0.20, 0.80, 0.60]with product 9.60e-02, indexes [1, 0, 0].

Here is a program in java to generate/print them: https://repl.it/repls/FilthyGreatRotation (all the logic is in printWholeCartesianProduct() method)
This program generates them in lexicographic order and then sorts the whole set by product.

Question: Is there an easy way to actually generate the combos in correct order in the first place?

The reason for this: I don’t have the lists in the first place, only iterators over some sorted collections of numbers. Possibly veeery long, length not known ahead of time, but it is known that the numbers in each iterator are sorted.

MVCE to play with (same as in https://repl.it link above):

import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringJoiner; import java.util.function.Consumer; import java.util.stream.Collectors;  public class Main {      public static void main(String[] args) {         List<List<Double>> data = createData();         printWholeCartesianProduct(data);     }      public static List<List<Double>> createData() {         double[] a1 = new double[]{0.70, 0.20, 0.10};         double[] a2 = new double[]{0.80, 0.10, 0.05, 0.05};         double[] a3 = new double[]{0.60, 0.15, 0.14, 0.10, 0.01};         return createData(a1, a2, a3);     }      public static void  printWholeCartesianProduct(List<List<Double>> data) {         final DecimalFormat df = new DecimalFormat("0.00");          // print input data         String matrix = data.stream()             .map(l -> l.stream().map(df::format).collect(Collectors.joining(", ")))             .map(row -> "[" + row + "]")             .collect(Collectors.joining("\n"));         System.out.println("Input data:\n" + matrix);          // collect combos as they are generated         final List<Combo> combos = new ArrayList<>();         Consumer<int[]> callback = indexes -> {             double[] v = new double[indexes.length];             double prod = 1;             for (int i = 0; i < indexes.length; i++) {                 List<Double> col = data.get(i);                 int index = indexes[i];                 v[i] = col.get(index);                 prod *= v[i];             }             combos.add(new Combo(prod, v, indexes.clone()));         };          // generate combos         int[] c = new int[data.size()];         int ptr = c.length - 1;         while (ptr >= 0) {             callback.accept(c);             c[ptr]++; // increment             if (c[ptr] == data.get(ptr).size()) { // carry                 do {                     ptr--;                 } while(ptr >= 0 && c[ptr] == data.get(ptr).size() - 1);                 if (ptr < 0) {                     break;                 }                 c[ptr]++;                 // zero out                 while (++ptr <= c.length - 1) {                     c[ptr] = 0;                 }                 ptr = c.length - 1;             }         }          // cheating - sort after generation and print result         combos.sort((o1, o2) -> Double.compare(o2.product, o1.product));         StringBuilder sb = new StringBuilder();         double totalP = 0;         for (int i = 0; i < combos.size(); i++) {             sb.append(String.format("%04d: ", i)).append(combos.get(i)).append("\n");             totalP += combos.get(i).product;         }         System.out.printf("Cartesian product in descending product (total p=%.3e):\n%s", totalP, sb.toString());     }      public static List<Double> asList(double[] a) {         return Arrays.stream(a).boxed().collect(Collectors.toList());     }      public static List<List<Double>> createData(double[]... arrays) {         final List<List<Double>> vals = new ArrayList<>();         Arrays.stream(arrays).forEachOrdered(a -> vals.add(asList(a)));         return vals;     }      static class Combo {         final double product;         final double[] vals;         final int[] indexes;          Combo(double product, double[] vals, int[] indexes) {             this.product = product;             this.vals = vals;             this.indexes = indexes;         }          @Override         public String toString() {             return new StringJoiner(", ", Combo.class.getSimpleName() + "[", "]")                 .add("product=" + String.format("%.2e", product))                 .add("vals=[" + Arrays.stream(vals).boxed().map(v -> String.format("%.2f", v)).collect(                     Collectors.joining(", ")) + "]")                 .add("indexes=" + Arrays.toString(indexes))                 .toString();         }     } } $$$$ 

## How to get sorted Gnome usability issues in Desktop?

I’ve instaled Ubuntu 19.04 from scratch after an issue with my old ubuntu installation.

I’ve found that now it uses Gnome instead of Unity. I like gnome, but I have a couple od important usability issues that I assume are easily configurable, and I just don’t know how to.

1. The full name of each file used to appear in Desktop icons, and if it were too long, when I clicked on the icon the full name would appear, even in long names.

Not now, as you can see:

1. Besides that, as you can see in the image attached, if I click on an image, the preview won’t appear either.

2. When doing anything in dektop before, like deleting a icon or moving it, I could easily press CTRL + Z and it would undo the action. How may I do that now?

Please note that I’ve installed Gnome Tweaks.

## Problema con listas en Python sin el uso de sort o sorted

Desarrolla el programa mezcla_ordena_listas.py que permitirá obtener de una lista ordenada de números enteros de menor a mayor a partir de dos listas de números enteros. Los valores individuales de las listas de entrada los captura el usuario uno por uno y posteriormente se unirán ambas listas para luego ordenarlas en forma ascendente (de menor a mayor valor). Tu programa deberá permitir la captura de los valores enteros de las listas sin hacer uso de mensajes (leyendas) al usuario y mostrará el resultado en la forma en que se indica más adelante.

Para ordenar:

No puedes usar la función sort o sorted ni ninguna función que ya ordene. Tendrás que escribirla tú. Si usas alguna función de estas no tendrás puntos extras.

Te recomiendo hacer una función llamada ordena(lista) que recibe una lista y regresa una lista ordenada.

El algoritmo para ordenar sería mas o menos así:

Por cada elemento en la lista, se hará una pasada a la lista  En cada pasada, se irá checando el elemento i con el i+1 y si el elemento en i es mayor al elemento que esta en i+1, intercambiarlos, seguir revisando hasta uno antes del final (para que en i+1 no te salga un index out of range. De esta forma,  el número mayor se irá 'empujando' hasta el final y no es necesario volver a revisar ese elemento (tu rango puede ir disminuyendo cada pasada).  Si no hubo intercambios, quiere decir que ya todo esta en orden y no es necesario hacer mas pasadas (puedes usar una variable booleana para saber si hiciste un intercambio o no) 

## Creating a priority search tree to find the number of points in the range [-inf, qx] X [qy, qy’] from a set of points sorted on y-coordinates

A priority search tree can be constructed on a set of points P in O(n log(n)) time but if the points are sorted on the y co-ordinates then it takes O(n) time. I find algorithms for constructing the tree when the points are not sorted.

I figured out a way to do this as follows:

1. Construct a BST on the points. Since the points are sorted then it will take O(n) time

2. Min-Heapify the BST on the x-coordinates This will take theta(n) time

So total time complexity will be O(n)

Is this a valid approach to construct a Priority Search Tree in O(n) time??

## How to push items to the top or bottom of the list in alphabetically sorted lists?

This question is not related to any specific scenario, platform or product, and it’s more of an end-user UX rather than a design of UX. It applies to various use cases and platforms. One specific example which prompted me to ask this question is the notebooks list in Evernote – I’d like to push my notebook called “Archives” to the bottom of the list – it’s right at the top otherwise. Another cases are naming the files and folders on a computer.

There are certain lists which are sorted alphabetically and there’s no way to re-arrange them. In general, this is quite practical as it makes it easier to find the items when there are plenty of them and there’s no need to arrange them manually.

However, sometimes you want to push certain items on the list to the top or to the bottom. And the only way to do that is to prefix the item with a certain symbol.

So:

• For pulling items to the top, the most common I’ve used is !, so your Requirements item becomes ! Requirements. Other nice options are ~ or -.
• For pushing to the bottom however, one obvious symbol is “z”, so if the item is named Archives, you name it zzz-Archives or zzz Archives.

While the exclamation mark and other non-alpha symbols seem OK, I find zzz` knocks off the visual “tidiness” of a list.

I am wondering if anyone used or seen more elegant solutions to pushing and pulling?