Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuro

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
012345678901234567890123456789012345678901234567890123456789
Ieri
012345678901234567890123456789012345678901234567890123456789
Visualizzazioni totali
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Ordinamento
Ordinamento
Sorting ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Discussioni

Guida a Ordinamento · 5/6

Practice Problems

Per ora questo capitolo è disponibile solo in inglese.

Most sorting problems are not "implement a sort" but "sort first, then the rest is easy". The four problems below practice sort-then-scan, multi-key ordering, custom comparators and reusing the merge step. Try each one before reading the solution.

Problem 1. Merge room bookings

Room bookings are given as (start, end) pairs of integers in no particular order. Merge bookings that overlap or touch, and return the periods when the room is actually in use, ordered by start time. For [(9, 11), (13, 15), (10, 12), (15, 16)] the answer is [[9, 12], [13, 16]].

Approach: after sorting by start time, a booking can only overlap the last merged period. Scan in order; if the current start is at most the last end, extend that end, otherwise open a new period. Sorting costs O(n log n) and the scan O(n).

def merge_bookings(bookings):
    result = []
    for start, end in sorted(bookings):
        if result and start <= result[-1][1]:
            result[-1][1] = max(result[-1][1], end)
        else:
            result.append([start, end])
    return result

print(merge_bookings([(9, 11), (13, 15), (10, 12), (15, 16)]))  # [[9, 12], [13, 16]]

Problem 2. Contest leaderboard

Each contestant has (name, score, seconds). Rank by score descending, then by time ascending, then by name alphabetically.

Approach: one tuple key expresses all three criteria, and negating the numeric score turns it into descending order. If a criterion that cannot be negated (such as a string) must be descending, run several stable sorts from the least to the most significant criterion. Python's reverse=True preserves stability too.

players = [("lee", 90, 300), ("kim", 95, 410), ("park", 90, 280), ("choi", 90, 300)]

ranked = sorted(players, key=lambda p: (-p[1], p[2], p[0]))
print([p[0] for p in ranked])  # ['kim', 'park', 'choi', 'lee']

# The same result with repeated stable sorts, least significant key first
step = sorted(players, key=lambda p: p[0])
step = sorted(step, key=lambda p: p[2])
step = sorted(step, key=lambda p: p[1], reverse=True)
print([p[0] for p in step])    # ['kim', 'park', 'choi', 'lee']

Problem 3. Largest concatenated number

Given non-negative integers, arrange them so that their concatenation is the largest possible number, and return it as a string. For [3, 30, 34, 5, 9] the answer is "9534330". If all values are zero, return "0".

Approach: sorting numerically or lexicographically fails on pairs like 3 and 30. Instead compare two strings a and b by whichever of a + b and b + a is larger. This comparison is transitive, so it is a valid sort order. Strip leading zeros so that becomes .

Domande su questo capitolo?
Capitolo precedenteComplexityCapitolo successivoReal-World Use
"000"
"0"
from functools import cmp_to_key

def largest_number(nums):
    words = [str(n) for n in nums]

    def compare(a, b):
        if a + b > b + a:
            return -1   # a goes first
        if a + b < b + a:
            return 1
        return 0

    words.sort(key=cmp_to_key(compare))
    return "".join(words).lstrip("0") or "0"

print(largest_number([3, 30, 34, 5, 9]))  # 9534330
print(largest_number([0, 0]))             # 0

Problem 4. Count out-of-order pairs

Count the pairs i < j with a[i] > a[j] (inversions) in an integer array of up to 200,000 elements. For example, [3, 1, 2] has two: (3, 1) and (3, 2).

Approach: checking every pair is O(n²), far too slow. During the merge step of merge sort, when right[j] is taken, the len(left) - i elements still waiting on the left are all larger and originally came earlier, so each forms an inversion. Adding these counts yields the answer in O(n log n) while sorting.

def count_inversions(a):
    def solve(items):
        if len(items) <= 1:
            return items, 0
        mid = len(items) // 2
        left, x = solve(items[:mid])
        right, y = solve(items[mid:])
        merged, i, j, cross = [], 0, 0, 0
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                merged.append(left[i])
                i += 1
            else:
                merged.append(right[j])
                j += 1
                cross += len(left) - i
        merged += left[i:] + right[j:]
        return merged, x + y + cross

    return solve(list(a))[1]

print(count_inversions([3, 1, 2]))        # 2
print(count_inversions([5, 4, 3, 2, 1]))  # 10

Equal values are not inversions, so the left element must be taken on ties (<=). Using < would count equal pairs by mistake.

Summary

  • Interval problems usually start with "sort by start, then scan once".
  • Use tuple keys for multiple criteria, and repeated stable sorts when a criterion cannot be negated.
  • Custom comparators work only when they are consistent (transitive).
  • The merge step of merge sort is a tool for counting order relations such as inversions.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.